简体   繁体   中英

How to return value to function and access it via a variable

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.
        })
    }
}

You could turn checkProfile into a Promise so you can then use async/await in other function calls

async checkProfile (user) {
    let p = {
      username: user,
      key: '00'
    }
    const d = await this.postMethod(p).toPromise()
    return d['code'] == '000' ? true : false;
}
let a = await myService.checkProfile(this.user);

You will also want to mark your component function as async. In my opinion this is all a lot easier as you don't have to handle multiple subscriptions and remembering to unsubscribe.

I think you should return your postMethod

like this:

checkProfile (user) {
    let p = {
      username: user,
      key: '00'
    }
    return this.postMethod(p).subscribe(
      d => {
        return d['code'] == '000' ? true : false;
      }
    )
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM