Угловой объект машинописи не определен в начале, что приводит к неопределенной ошибке - PullRequest
0 голосов
/ 03 июля 2019

Как мне вызвать службу, чтобы сначала создать объект, чтобы избежать неопределенной ошибки? Служба это просто вернуть this.httpclient.get ("serviceUrl") TS файл

export class AboutmeComponent implements OnInit {

  personalInformation: Object;

  constructor(private portfolioService: PortfolioService) {
    this.getPersonalInformation();
  }

  ngOnInit() {
  }

  getPersonalInformation(){
    return this.portfolioService.getPersonalInformation().subscribe(data=>{
      console.log(data);
      this.personalInformation = data;
    });
  }
}

HTML-файл

<p>aboutme works!</p>
<mat-grid-list cols=4>
    <mat-grid-tile [colspan]=3>

    </mat-grid-tile>
    <mat-grid-tile [colspan]=1>
        <img [src]="personalInformation.profilePhotoUrl" alt="">
    </mat-grid-tile>
</mat-grid-list>

ошибка

Cannot read property 'profilePhotoUrl' of undefined

Ответы [ 2 ]

2 голосов
/ 03 июля 2019

Хотя решение, предоставляемое @indrajeet, подойдет. Я хотел бы предложить решение, используя async трубу, как это -

component.ts

export class AboutmeComponent implements OnInit {

  personalInformation$: Observable<any>;

  constructor(private portfolioService: PortfolioService) {
  }

  ngOnInit() {
    this.personalInformation$ = this.portfolioService.getPersonalInformation();
  }
}

HTML

<p>aboutme works!</p>
<mat-grid-list cols=4>
    <mat-grid-tile [colspan]=3>

    </mat-grid-tile>
    <mat-grid-tile [colspan]=1>
        <ng-container *ngIf="(personalInformation$ | async) as personalInformation">
            <img [src]="personalInformation.profilePhotoUrl" alt="">
       </ng-container>
    </mat-grid-tile>
</mat-grid-list>

Наличие async канала в шаблоне позволяет избежать подписки на наблюдаемое в файле TS. async заботится о развертывании значения из наблюдаемого. Это также гарантирует отмену подписки наблюдаемого [за сценой] после разрушения компонента.

2 голосов
/ 03 июля 2019

component.ts

export class AboutmeComponent implements OnInit {

  personalInformation: Object;

  constructor(private portfolioService: PortfolioService) {
  }

  ngOnInit() {
    this.portfolioService.getPersonalInformation().subscribe(data=>{
      console.log(data);
      this.personalInformation = data;
    });
  }
}

HTML

<p>aboutme works!</p>
<mat-grid-list cols=4>
    <mat-grid-tile [colspan]=3>

    </mat-grid-tile>
    <mat-grid-tile [colspan]=1>
        <img [src]="personalInformation?.profilePhotoUrl" alt="">
    </mat-grid-tile>
</mat-grid-list>
...