angular - 在 Typescript 中定义一个属性以防止 Angular 中的编译错误

标签 angular typescript

export class ListService {
    ...
    getAllLists(): Observable<List[]> {
        let URI = `${this.serverApi}/bucketlist/`;
        return this.http.get<List[]>(URI)
            .pipe(
                map(res => <List[]>res.lists)
            );
    } 
}

ng serve编译时,显示如下错误

错误 TS2339:属性“lists”在类型“List[]”上不存在。

已知res.listsList[]类型。为 res 定义属性以便代码编译无误的更好方法是什么?

这是一个res样本

{
  "success": true,
  "lists": [
    {
      "_id": "5c6673abeb64adb41ec6dfaf",
      "title": "First Project"
    }
  ]
}

尝试的解决方案

interface Response {
    success: boolean;
    lists: List[];
}
export class ListService { 
    getAllLists(): Observable<List[]> {
        ...
        return this.http.get<Response>(URI)
            .pipe(
                map(res => res.lists)
            );
    }
}

最佳答案

长话短说

res看起来像一个对象,而不是 List[] .所以http.get<List[]>行不通。

试试这个

interface MyResponse {
  success: boolean;
  lists: List[];
}

export class ListService {
    ...
    getAllLists(): Observable<List[]> {
        let URI = `${this.serverApi}/bucketlist/`;

        // Replace 'List[]' with 'MyResponse' here
        return this.http.get<MyResponse>(URI)
            .pipe(
                map(res => res.lists)
            );
    } 
}

说明

当你写 this.http.get<List[]>(URI)您的编译器期待类型为 Array of List 的响应。问题是响应与签名不匹配。正如你所说res看起来更像

{
  "success": true,
  "lists": [
    {
      "_id": "5c6673abeb64adb41ec6dfaf",
      "title": "First Project"
    }
  ]
}

您可以看到它不是一个数组,所以 List[]行不通

关于angular - 在 Typescript 中定义一个属性以防止 Angular 中的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54745876/

相关文章:

angular - RxJs withLatestFrom/combineLatest : ignore second source when nothing is emitted

javascript - 如何从 Angular 服务中的行为主体中提取数据?

javascript - 将 Javascript 成员变量转换为 Typescript 成员变量

angular - 无法获取未定义或空引用的属性 'toLowerCase'

angular - 使用 Angular 中的 RxJs,我只需要完成在组件中创建的 Observables 吗?

javascript - 如何正确地将 WASM 集成到 Angular 服务中

Angular 2 : What is the exact difference between private and public attributes in components?

javascript - 类型 'Observable<{}[]>' 无法转换为类型 'AngularFireList<any[]>'

reactjs - 要求至少将一个 prop 传递给组件 [typescript]

angular - 让我的 Accordion 动态响应?