網站搜尋

typescript - 類型 'Promise' 缺少以下屬性 angular


我正在使用 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();
        });
    }

路徑=端點

答案#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);

但是你正在使用 service,而不是 HttpClient,而且你沒有指定你的返回...

你的 getUsers() 函數會返回 1 個還是多個使用者?如果你返回的是列表,你應該簡單地將你的請求變數改為 users: User[];