我正在处理一个Angular 7应用程序,我正在尝试将HTTP get调用的值赋给组件中的变量。调用是返回和Item [],它是我的应用程序中的一个接口,并将其分配给我的组件中的局部变量,该变量也是Item []类型。 observable返回数据正常,但在尝试赋值后,局部变量仍未定义。
我试图将我的局部变量定义为item: Item[]
以及item: Item[] = []
。
我正在使用解析器来调用我的服务(按预期工作)
@Injectable()
export class ShopItemResolver implements Resolve<Item[]> {
constructor(private shopSvc: ShopService, private router: Router,
private alertify: AlertifyService) {}
resolve(route: ActivatedRouteSnapshot): Observable<Item[]> {
return this.shopSvc.getItems().pipe(
catchError(error => {
this.alertify.error('Problem retrieving shop items');
this.router.navigate(['/home']);
return of(null);
})
);
}
}
来自我的服务的代码调用API(按预期工作)
getItems(): Observable<Item[]> {
return this.http.get<Item[]>(this.appBase + 'inventory/items');
}
这是我的组件,它利用激活的路径来获取数据。
items: Item[];
constructor(private shopSvc: ShopService, private alertify: AlertifyService,
private route: ActivatedRoute) { }
ngOnInit() {
this.route.data.subscribe(data => {
this.items = data.items;
});
}
我期待this.items = data.items
导致this.items
填充订阅数据,但它仍未定义。
我在data.items中订阅的结果如下所示
(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {id: "M5RDENDIEMVQDNT7ZBSDILES", name: "Black Shirt", description: "test shirt", categoryId: "WWVHETDEBLZMC56CXRLXHQD3", categoryName: "Men's Clothing", …}
1: {id: "AQ4QSJBZAXSLFYMM5OUVMN5S", name: "White shirt", description: "test white shirt", categoryId: "WWVHETDEBLZMC56CXRLXHQD3", categoryName: "Men's Clothing", …}
2: {id: "J2BUKL5ISUES7MG4HX6AS5YA", name: "leather bracelet", description: "test bracelet", categoryId: "NDDQF73XMP2ZYSMSPIMC5MVT", categoryName: "Jewelry", …}
3: {id: "VX24EA6FUSUQAPYND5WKXEZH", name: "Wallet", description: "test wallet", categoryId: "6LNWE4A6MKX3H4ZKBCPDEU3E", categoryName: "Wallets", …}
4: {id: "FPLFHLVWSXOQWVB3K73YZYAT", name: "grey shirt", description: "test womens shirt", categoryId: "FDPF5P2V3FJGSGTYUBC2QHYC", categoryName: "Women's Clothing", …}
5: {id: "7HQV75KL6CSXEPH3KLCO6QCK", name: "red shirt", description: "test womens shirt", categoryId: "FDPF5P2V3FJGSGTYUBC2QHYC", categoryName: "Women's Clothing", …}
这是Item接口
export interface Item {
Id: string;
Name: string;
Description: string;
CategoryId: string;
CategoryName: string;
Price: number;
}
实际上发生的是,在订阅完成之前加载模板,您可以使用加载直到获取数据为止
在ts文件中
this.is_ready = false;
this.route.data.subscribe(data => {
this.items = data.items;
this.is_ready = true;
});
在HTML中
<div *ngIf="is_ready">
// display data
</div>
我解决了这个问题问题是Typescript接口的格式。当API返回数据时,它全部设置为小写变量名称,并且接口在第一个字母上期望大写。将界面更改为驼峰案例有效。界面以这种方式格式化的原因是因为非正统的linting规则已被更改并且不再强制执行此操作。