无法在订阅角度的ngoninit中获取值

时间:2019-01-11 12:45:08

标签: angular subscribe ngoninit

我不明白为什么我的对象总是在angular的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"
}

2 个答案:

答案 0 :(得分:1)

@ Devozor92这样更改组件,

 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) => 
       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

我希望这能解决您的问题:)

答案 1 :(得分: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 
  }