0

I try to execute a for each in my ngOnInit method (i use Angular 4+). But it doesn't perform

there is my code :

export class ObjectDetailComponent implements OnInit {

  public object$: Object ;
  private member$: Object ;
  private _sellers = [];
  private _seller: string;


  constructor(private route: ActivatedRoute, private _cookieService: CookieService,
              private _objectService: AuctionedObjectService, private _memberService: MemberService, private _sellerService: SellerService) {
    this.route.params.subscribe( params => this.object$ = params.id );
  }

  ngOnInit() {


    this._objectService.getObject(this.object$).subscribe(
      data => this.object$ = data);

    this._memberService.getMember(Number(this._cookieService.get('login')))
      .subscribe(data2 => this.member$ = data2);

    this._sellerService.getSellers()
      .subscribe(data3 => this._sellers = data3);

    this.sellerUser();

   }


   public sellerUser(){
    for(const seller of this._sellers){
      if(Number(this._cookieService.get('login')) === seller.idUser){
        this._seller = seller.username;
        break;
      }
    }
   }

  }

The sellerUser() doesn't work :/

Ali
  • 2,702
  • 3
  • 32
  • 54
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Igor Dec 06 '18 at 02:46

1 Answers1

0

Use your synchronous logic after you are sure you have got the result, use this.sellerUser(); under your Subscripition. In your current implementation, this.sellerUser(); will get called before your subscription is over(coz subscription is async and will be executed at last after executing all your sync code)

this._sellerService.getSellers()
  .subscribe(data3 => {
     this._sellers = data3;
     this.sellerUser(); // here
 });
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51