开始时未定义角度打字稿对象,导致未定义错误

时间:2019-07-02 23:16:28

标签: angular service

我如何首先调用服务来创建对象以避免未定义的错误? 该服务仅返回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 个答案:

答案 0 :(得分:2)

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>

答案 1 :(得分:2)

尽管@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负责将值从可观察值中解包出来。一旦组件销毁,它还可以确保取消订阅[可观察到的[幕后]。