分配.subscribe结果后未定义的接口数组

时间:2019-04-02 12:58:39

标签: angular typescript

我有一个正在使用的Angular 7应用程序,正在尝试将HTTP get调用的值分配给组件中的变量。调用是返回Item [](这是我的应用程序中的接口),并将其分配给组件中也是Item []类型的局部变量。可观察对象返回的数据很好,但是尝试分配后,局部变量仍然未定义。

我尝试将局部变量定义为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;
    }

2 个答案:

答案 0 :(得分:1)

实际上是这样,模板在订阅完成之前就已加载,您可以使用加载直到像这样获取数据

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

答案 1 :(得分:0)

我解决了这个问题。问题是Typescript接口的格式。当API返回数据时,所有数据都设置为小写的变量名,并且接口期望第一个字母大写。将界面更改为驼峰式情况有效。格式化接口的原因是因为更改了一个非正统的掉毛规则,并且不再强制执行此操作。