类型'Promise <any>'缺少以下属性angular

时间:2019-05-10 20:10:47

标签: typescript http angular7

我正在用angular7建立与系统的http连接。但是,这给模块带来了错误。创建创建请求时出现以下消息:

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

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();
        });
    }
  

path =端点

2 个答案:

答案 0 :(得分:0)

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

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[];

答案 1 :(得分:0)

我发现了问题,只是更改了以下请求:

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