I have a method in my service where i wish to return true or false according to value gotten and access the value in my component.
My service file:
checkProfile (user) {
let p = {
username: user,
key: '00'
}
this.postMethod(p).subscribe(
d => {
return d['code'] == '000' ? true : false;
}
)
}
my component where i wish to know the value of the above:
let a = myService.checkProfile(this.user);
How do i get the method to return true or false so that i may be able to access it via the variable a
. Right now a
is undefined
checkProfile should return an Observable, use map to transform the value to a boolean. Read more about it here https://www.learnrxjs.io/operators/transformation/map.html
checkProfile(user):Observable<boolean> {
let p = {
username: user,
key: '00'
}
return this.postMethod(p).pipe(map(d=>{
return d['code'] == '000' ? true : false
}))
}
and in the component
export class YourComponent{
check$:Observable<boolean> // if you want it to subscribe multiple times
constructor(private myService:MyService){
this.check$: Observable<boolean> = myService.checkProfile(this.user); // if
you want it to subscribe multiple times
}
// the other approach, if you only want to subscribe here
someMethod(){
this.myService.checkProfile(this.user).subscribe((check:boolean)=>{
let a =check // here you have the value in ts.
})
}
}