Невозможно получить значение в ngoninit при угловой подписке - PullRequest
0 голосов
/ 11 января 2019

Я не понимаю, почему мой объект всегда "неопределен" на ngoninit на angular. Я прошу о моем проекте 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 голосов
/ 11 января 2019

Не определено, потому что у вас еще нет данных.

     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 
  }
0 голосов
/ 11 января 2019

@ 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

Я надеюсь, что это решит вашу проблему:)

...