【问题标题】:Type 'Promise<any>' is missing the following properties angular类型 'Promise<any>' 缺少以下属性
【发布时间】:2019-05-11 07:04:16
【问题描述】:

我正在 angular7 中与我的系统建立 http 连接。但是,它在模块中给出错误。当我创建 get 请求时出现此消息:

Type 'Promise<any>' is missing the following properties from type 'User': id, user, email

模块:

export class User { 
  id: number
  user: string
  email: string
}

请求:

users: User;

    this.userService.getUsers().subscribe(
          response => {
            if (!response) {
              console.log(Error)
            } else {
              this.users = response
            }
          })

http 获取:

getUsers() {
        return this.service.get(this.endpoint)
        .map((response) => {
            return response;
        });
    }

服务:

standardHeaders() {
        const headers = new HttpHeaders();
        headers.append('Content-Type', 'application/json');
        if (this.authToken) {
            headers.append('X-Authorization', this.authToken);
        }
        return { headers: headers };
    }

 get(path: string) {
        return this.http.get(this.url + path, this.standardHeaders()).map((response: Response) => {
            return response.json();
        });
    }

路径 = 端点

【问题讨论】:

  • 那么console.log(response)的输出是什么?
  • 我还没有执行请求,因为后端 api 没有 100% 完成。

标签: typescript http angular7


【解决方案1】:

我发现了问题,只是改变了请求:

users: User;

this.userService.getUsers().subscribe(
          response => {
            if (!response) {
              console.log(Error)
            } else {
              this.users = response
            }
          })

为:

this.userService.getUsers().subscribe(
      response => {
        if (!response) {
          console.log(Error)
        } else {
          console.log(response)
          let users : User[] = response
        }
      })

【讨论】:

    【解决方案2】:

    很难从您的代码中看出,我通常如何使用 HttpClient 使用通用 get 来执行这样的请求

    public get(id: number): Observable<className> {
      return this._http.get<className>(`${this._baseUrl}/${id}`);
    }
    

    然后像这样使用

    this.service.get(id).subscribe(x => this.myClass = x);
    

    但是你使用的是服务,而不是HttpClient,并且你没有指定你的回报……

    您的getUsers() 函数是否返回 1 或 manu 用户? 如果您返回一个列表,您只需将您的请求变量更改为users: User[];

    【讨论】:

    • 他正在返回一个列表。但是,当我按照您的建议进行更改时,错误变为:Type 'Promise' is missing the following properties from type 'User[]': length, pop, push, concat, and 26 more.
    • 我添加了相关服务。
    猜你喜欢
    • 2019-12-24
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 2020-09-12
    • 2021-04-02
    • 2019-09-11
    • 1970-01-01
    • 2019-04-28
    相关资源
    最近更新 更多