简体   繁体   中英

Angular ngOnInit()

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 :/

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

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