数据不属于Angular模板

时间:2016-03-09 16:21:58

标签: javascript angular

我有组件:

@Component({
    selector: 'fx-content',
    templateUrl: 'app/modules/localization/html/localizationList.html',
    providers: [
        LocalizationService,
        HttpClient
    ]
})

export class LocalizationComponent implements OnInit {
    private localizationService :LocalizationService;

    public data :Array<string>;

    constructor(localizationService :LocalizationService) {
        this.localizationService = localizationService;
    }

    ngOnInit() {
        this.getLocalization();
    }

    getLocalization(){
        this.localizationService.getLocalization().localizationList.subscribe((data) => {
            this.data = data;
            console.log("DATA:",this.data)
        });
    }
}

服务:

export class LocalizationService {
    private httpClient :HttpClient;

    public localizationList;

    constructor(httpClient :HttpClient) {
        this.httpClient = httpClient;
    }

    public getLocalization(){
        this.localizationList = this.httpClient.get('localization').map(res => res.json());
        return this;
    }
}

和templale:

<table class="lst">
    <thead>
    <tr>
        <th>Label</th>
        <th>Path</th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="#item of data.locales">
        <td>
            <a>{{item.name}}</a>
        </td>
        <td>
            {{item.path}}
        </td>
    </tr>
    </tbody>
</table>

当我转到此页面时,出现错误:EXCEPTION: TypeError: Cannot read property 'locales' of undefined。同时,控制台显示带有数据的普通对象。我认为这个错误是因为他在从服务接收数据之前尝试渲染模式。是这样吗?如何让它正常工作?

1 个答案:

答案 0 :(得分:1)

您需要利用Elvis运算符:

<tr *ngFor="#item of data?.locales">
    <td>
        <a>{{item.name}}</a>
    </td>
    <td>
        {{item.path}}
    </td>
</tr>
更新服务后

export class LocalizationService {
  private httpClient :HttpClient;

  constructor(httpClient :HttpClient) {
    this.httpClient = httpClient;
  }

  public getLocalization(){
    return this.httpClient.get('localization').map(res => res.json());
  }
}

和组件:

getLocalization(){
  this.localizationService.getLocalization().subscribe(
    (data) => {
      this.data = data;
    }
  );
}

实际上你可以直接从服务中返回observable并让组件订阅它......