gpt4 book ai didi

javascript - 数据不属于 Angular 模板

转载 作者:行者123 更新时间:2023-12-03 07:28:40 26 4
gpt4 key购买 nike

我有组件:

@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;
}
}

还有寺庙:

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

当我转到此页面时,出现错误:异常:类型错误:无法读取未定义的属性“区域设置”。同时,控制台显示一个带有数据的正常对象。我认为这个错误是由于他试图在从服务接收数据之前渲染模式。是这样吗?如何使其正常工作?

最佳答案

为此,您需要利用 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;
}
);
}

事实上,您可以直接从服务返回可观察对象并让组件订阅它......

关于javascript - 数据不属于 Angular 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35897047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com