NAtivescript : Not able to get the updated value from service.ts to the component.ts


#1

Hi,I am facing issue in getting the updated boolean varibale that is set in my service.
When i am trying to access the varaible in my component ,it is giving me always the default value of the variable.(initiazed in service)
The boolean varaible is upadtaed in servce using get and set.
but when i am trying to get the variable in component iam not getting the latest value

Please help how do pass the service varaible to component.


#2

Is the service an injectable? Are you sure it isnt making a new instance everytime?


#3

yes its injectible…

here is my service code :

lAlert$: Observable;

private lAlertSubject: Subject<boolean>;

constructor() {
    this.lAlertSubject = new Subject<boolean>();
    this.lAlert$ = this.lAlertSubject.asObservable();
} 

updating this variable in below function :

login(username:string,password:string,pTransPassword:string,loggedinuser:LoggedInUser){

 var hc = this;

var response= http.getString({
url: “http://10.1.101.23:6080/stocks/LoginServlet?Thick%20Client=Y&compressed=N&mobileVersionNumber=1.21&MOSType=Android&JMCP=Y&WEB=Y&USLOGINID="+username+"&USPassword="+password+"&USTransactionPassword=”+pTransPassword ,
method: ‘GET’,
headers: {
// ‘Authorization’: ‘Basic ZWx1c3VhcmlvOnlsYWNsYXZl’,
// ‘x-uuid’: ‘aHR0cHdhdGNoOmY’,
‘x-version’: ‘4.2.0’,
‘x-env’: ‘DEVELOPMENT’,
},
}).then(function(response) {
alert("Login response "+ " " + response);
//console.log(‘Https.request response’, response)tns run android
hc.presponse=[];
hc.presponse=hc.loginhandleResponse(loggedinuser,response);
console.log(“presponse*****” +hc.presponse);

}).
catch(function(error) {
console.error(‘Https.request error’, error);
// alert(“Invalid Credentials”);

})
return hc.presponse;
}
public loginhandleResponse(loggedinuser:LoggedInUser,loginresponse:string){
console.log(“login handle repsonse”);
let logindata:string[][]= this.makeArray(loginresponse);
console.log(“logindata-----------------------” +logindata)
this.lValues=[];
let lResult:string=loginresponse;
if (lResult.charAt(0)==‘0’)
{
console.log(“lResult.charAt(0)” +lResult.charAt(0))
if ((logindata.toString().length>5)&&((logindata[5][0].toString()==(“14”))||(logindata[5][0].toString()==(“15”))||(logindata[5][0].toString()==(“16”))))
{ console.log(“logindata ***”)

				if (logindata[5][1].substring(0,5)==("Change"))
				{
					console.log("logindata1")
					this.setAlertMessage(logindata[5][1]); 
					this.lAlertSubject.next(true);
					 this.lValues[0]=logindata[3][0];
					 this.lValues[1]=logindata[1][1];
					 this.lValues[2]=logindata[1][0];
					this.lValues[3]=logindata[1][4]; 
				}
				else
				{
					console.log("logindata2")
					 loggedinuser = new LoggedInUser();
					loggedinuser.setLoginKey(logindata[1][1]);
					//Log.i("Fow","ok5");
					this.setAlertMessage(logindata[5][1]);
					//System.out.println(" ok5 Else:"+loginData[5][1]);
					this.lAlertSubject.next(true);
					 //lValues = {loginData[3][0],loginData[1][1],loginData[1][0]};
					 this.lValues[0]=logindata[3][0];
					 this.lValues[1]=logindata[1][1];
					 this.lValues[2]=logindata[1][0];
					this.lValues[3]=logindata[1][4]; 
					 //Log.i("Fow","ok6");
                    console.log("get alert message:" +this.lAlertSubject.subscribe);
					 
					//PasswordExpiredPeriod lPasswordExpiredPeriod = new PasswordExpiredPeriod(lValues,this,lGD, userPassword.getString());
				}
				
				//added by bhairav
				//plogedInUser = new LogedInUser();
				
				if(logindata != null)
				{
				console.log("logindata1**" +logindata[1][0] + "**" +logindata[1][4] + "**"+logindata[1][1] + "**" +logindata[1][5]+"**" +logindata[1][2] + "**" +logindata[1][3]);
				loggedinuser.setUserId(logindata[1][0]);				
					loggedinuser.setLoginId(logindata[1][4]);				
					loggedinuser.setLoginKey(logindata[1][1]);				
					loggedinuser.setUserType(logindata[1][5]);				
					loggedinuser.setBackOfficeId(logindata[1][4]);				
					loggedinuser.setUserName(logindata[1][2]+" "+logindata[1][3]);
					
					 this.gCmnUrl= "Thick%20Client=Y&compressed=N&LoginKey="+logindata[1][1];
					 this.gCmnUrlNoUsid = "Thick Client=Y&LoginKey="+logindata[1][1];				
					loggedinuser.setCmnUrl(this.gCmnUrl);
					loggedinuser.setCmnUrlNoUsid(this.gCmnUrlNoUsid);				
				}
				else
				{
					this.lAlertSubject.next(false);
					this.setAlertMessage("Invalid Login. Please Try Again.");
                    console.log("get alert message:" +this.lAlertSubject);

				}

}
else
{

				console.log("logindata[3][0]" +logindata[3][0]);
                console.log("logindata[1][1]" +logindata[1][1]);
				console.log("logindata[1][0]" +logindata[1][0]);
				console.log("logindata[1][4]" +logindata[1][4]);
                console.log(this.lValues);
			
				this.lValues[0]=logindata[3][0];
                console.log(+this.lValues[0] + logindata[3][0])
				this.lValues[1]=logindata[1][1];
				this.lValues[2]=logindata[1][0];
				this.lValues[3]=logindata[1][4]; 		
				 
				this.lAlertSubject.next(false);
                console.log("get alert message:" +this.lAlertSubject);
			
			}
       }

and in component .ts :

currentBool: boolean;

constructor(private router:Router,private loginservice:LoginService) {
    loginservice.lAlert$.subscribe((newBool: boolean) => { this.currentBool = newBool; });
}

public submit()
{
console.log(“hello:” +this.username);

		 this.pResult=[];
		 this.pResult=this.loginservice.login(this.username,this.password,this.pTransPassword,this.loggedinuser);
		 
		 console.log("pResult******" +this.pResult);
		console.log("getalert*****:" +this.currentBool);
 
		if(this.currentBool == true){

			console.log("getalert*****:" +this.currentBool);
				if (this.loginservice.getAlertMessage().trim().indexOf("Change") >= 0 || this.loginservice.getAlertMessage().trim().indexOf("expired") >= 0) 
				{						
					//System.out.println("if 111111111111111");
					alert("Your Password has expired.Please change the password");
				} 

I am trying to call Login method in service which is a HTTP call and the response that iget from http call is formated to array by calling my own function (handle response).
I want to use the update value of lALertSubject from the service- which is defined as observable.


#4

is it possible for you to format that code a bit better? I’m just finding it a slight bit hard to read.


#5

Ok sorry.

Hope this helps you…

@Injectable()
export class LoginService {
lAlert$: Observable;
private lAlertSubject: Subject;
constructor() {
this.lAlertSubject = new Subject();
this.lAlert$ = this.lAlertSubject.asObservable();
}
login(username:string,password:string,pTransPassword:string,loggedinuser:LoggedInUser){
var hc = this;
var response= http.getString({
url: “http://10.1.101.23:6080/stocks/LoginServlet?Thick%20Client=Y&compressed=N&mobileVersionNumber=1.21&MOSType=Android&JMCP=Y&WEB=Y&USLOGINID="+username+"&USPassword="+password+"&USTransactionPassword=”+pTransPassword ,
method: ‘GET’,
},
}).then(function(response) {
alert("Login response "+ " " + response);
//console.log(‘Https.request response’, response)tns run android
hc.presponse=[];
hc.presponse=hc.loginhandleResponse(loggedinuser,response);
console.log(“presponse*****” +hc.presponse);
}).
catch(function(error) {
console.error(‘Https.request error’, error);
})
return hc.presponse;
//another function to handle the response above
public loginhandleResponse(loggedinuser:LoggedInUser,loginresponse:string){
console.log(“login handle repsonse”);

if(some condition){
this.lAlertSubject.next(true);
}
else{
this.lAlertSubject.next(fasle);
}
}
}

Now in my login component I am trying to call the login method of service which in turn calls the loginhandlereponse()–>in this method i am setting the boolean value to true or false.
just want to get the updated value of the boolean variable .

export class HomeComponent {
currentBool: boolean;
constructor(private router:Router,private loginservice:LoginService) {
loginservice.lAlert$.subscribe((newBool: boolean) => { this.currentBool = newBool; });
}
public submit()
{
console.log(“hello:” +this.username);

		 this.pResult=[];
		 this.pResult=this.loginservice.login(this.username,this.password,this.pTransPassword,this.loggedinuser);
		console.log("get the value of the boolean variable:" +this.currentBool);

}

also note that i have added providers[loginservice] in app.module.ts


#6

I’m not sure what loginservice.lAlert$.subscribe((newBool: boolean) => { this.currentBool = newBool; }); is supposed to do? I’ve not seen that been done before


#7

how will i get the value of the lAlert$ defined in service.
We need to subscribe the value of observable to get th eupdated value ,right?
i am new to angular and nativescript.
Please help …where and how can i get the updated value


#8

Going by the code you provide, lAlert$ never appears to get changed by your service.


#9

i am doing this :
this.lAlertSubject.next(true); (as per one example seen )
perviously i was using a normal olean variable and i was setting to true and false.but that too did not worked.
so now i am usn gobeservales and subject.
what im mising?


#10

how can i chnge the value?


#11

hello…how can we get a string response using http.get(“url”).map() function in angular 2 nativescript…
all exmaples show json reposnse only…but our servlet is sending string response…how can we map that repsonse pleas help


#12

Ideally you would want the server to send a json response. However, you can specify a text return in the request headers


#13

.text is not returning the final repsonse


#14

.text? What do you mean?


#15

return this.http.get(“http://10.1.101.23:6080/stocks/LoginServlet?Thick%20Client=N&compressed=N&mobileVersionNumber=1.21&MOSType=Android&MCP=Y&WEB=Y&USLOGINID="+username+"&USPassword="+password+"&USTransactionPassword=”+this.tpw)
.map(result =>result.text)


#16

I’ve never seen that before. If you want the result to be interpreted as a string in your app, you need to add an Accept-Type header of application/text