1

I have a function like one the below in

service.ts:-

itemList$: BehaviorSubject<any> = new BehaviorSubject([]);
    getItem() {
    this.http
    .get('APIURL Here')
    .subscribe((res: any) => {
    this.itemList$.next(res.data);
    });
    }

Below is my component.ts:-

constructor(private myService: MYService) {
    }
    matchItem(idtomatch:any){
    let matchStatus:boolean=false;
    this.myService.itemList$.subscribe((res: any) => {
    for (let val of res) {
    if(idtomatch === res.id){
    matchStatus = true;
    }
    else{
    matchStatus = false;
    }
    }
    });
    return matchStatus;
    }
this.matchItem(idtomatch) 

It should return true when idtomatch === res.id else it should return false while it's always returning false.

skindia
  • 21
  • 4
  • can you print that res inside subscribe method – Gopal Dec 17 '22 at 04:55
  • 1
    You are returning the value before the `subscribe` callback had any chance to run. – Tobias S. Dec 17 '22 at 04:55
  • @TobiasS. Fromwhere should i return – skindia Dec 17 '22 at 05:19
  • 1
    You can't return the value of `matchStatus` from the function because you are dealing with asynchronous calls here. Return an Observable instead. – Tobias S. Dec 17 '22 at 05:22
  • @Gopal inside the this.myService.itemList$.subscribe((res: any) => { console.log(res); }); I am getting the value. also matchStatus become true and false as per value but it's always returning false from let matchStatus:boolean=false; done know why matchStatus not being overwritwe as per the condition. – skindia Dec 17 '22 at 05:23
  • @TobiasS. Then how I can achieve my objective , can you please advise – skindia Dec 17 '22 at 05:34
  • @TobiasS. Then how can get goals , please advise – skindia Dec 17 '22 at 05:35
  • we don't know what your goals are – Tobias S. Dec 17 '22 at 05:56
  • @TobiasS. I want true OR false here this.matchItem(idtomatch) based on match that's it. – skindia Dec 17 '22 at 06:05
  • @TobiasS. any suggestion for me. – skindia Dec 17 '22 at 06:26
  • 1
    https://stackoverflow.com/questions/38291783/how-to-return-value-from-function-which-has-observable-subscription-inside this could be helpful for you – Gopal Dec 17 '22 at 06:47
  • Does this answer your question? [How to return value from function which has Observable subscription inside?](https://stackoverflow.com/questions/38291783/how-to-return-value-from-function-which-has-observable-subscription-inside) I'm voting to close, because I believe you have some misconceptions that need to be clarified first. You are trying to mix synchronous and asynchronous programming here. – Lukas-T Dec 19 '22 at 11:25

0 Answers0