1

我不明白为什么我的对象在角度上的 ngoninit 上总是“未定义”。我在我的 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"
}
4

2 回答 2

3

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

做一些改变,如下所示,

 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
  }

快乐编码.. :)

于 2019-01-11T13:08:02.390 回答
0

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

     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 
  }
于 2019-01-11T13:14:58.150 回答