订阅时无法在 ngoninit 中获取值 angular

Can't get value in ngoninit on subscribe angular

我不明白为什么我的对象在 angular 上的 ngoninit 上总是 "undefinned"。 我请求我的 api 项目,我得到了正确的回复。 当我 console.log 我的对象未定义 (ngoninit) 但在其他函数中我可以获得值。

我的问题是为什么以及如何才能在 ngoninit 中获取我的对象。

谢谢

我在邮递员上正确检索了我的回复 其他函数也检索

服务:

getById(id:string):Observable<Grower>{
   return this.http.get<Grower>(`${environment.apiUrl}/growers/${id}`);
}

查看模型:

export class GrowerDetails {

    adress:string;
    zip:string;
    city:string;
}

组件:

  growerService:GrowerService;

  detailsProfil: GrowerDetails;

  constructor(private authenticationService: AuthenticationService, growerService:GrowerService,
    private formBuilder:FormBuilder) { 
      this.growerService = growerService;
   }

  ngOnInit() {
    this.detailsProfil = new GrowerDetails();

    this.growerService.getById(this.decoded.nameid).subscribe(
      (data:Grower) => this.detailsProfil = {
            adress: data.adress,
            city: data.city,
            zip : data.zip

      },
      error => console.log(error) 
    );
console.log(this.detailsProfil); // undefinned

onSubmit(){
    console.log(this.detailsProfil); // ok
 }

邮递员:

{
    "lat": 0,
    "long": 0,
    "description": "test",
    "adress": "test",
    "zip": "test",
    "city": "test"
}

我们可以在订阅内部获得 detailsProfil 的值,但不能在订阅外部获得。因为 getById() 是一个 async 调用所以不会等待订阅完成执行。

像下面这样做一些改变,

 constructor(private authenticationService: AuthenticationService, growerService:GrowerService,
    private formBuilder:FormBuilder) { 
      //  this.growerService = growerService;  <- this line not required
   }

  ngOnInit() {
    this.detailsProfil = new GrowerDetails();

    this.growerService.getById(this.decoded.nameid).subscribe((data) => {
       console.log(data);            
       this.detailsProfil.adress = data.adress;
       this.details.city = data.city;
       this.details.zip = data.zip;
     },
      error => console.log(error));
     console.log(this.detailsProfil); // you will get detailsProfil Object
  }

快乐编码..:)

未定义,因为您还没有数据。

     ngOnInit() {
        this.detailsProfil = new GrowerDetails();

        this.growerService.getById(this.decoded.nameid).subscribe(
          (data:Grower) => {
             this.detailsProfil = {adress: data.adress,city: data.city,zip : data.zip };

             console.log(this.detailsProfil); // you can access here because you got it now.
          },
          error => console.log(error) 
        );

    console.log(this.detailsProfil); // you can't access here. it's still undefined 
  }