簡體   English   中英

Angular 6 Http訂閱問題:類型“ Response”上不存在屬性“ userInfo”

[英]Angular 6 Http Subscribe issue: Property 'userInfo' does not exist on type 'Response'

我正在使用angular6

Service.ts

post(url, body, options): Observable<Response>{
        let headers = new Headers();
        this.createAuthorizationHeader(headers);
        return this.http.post(this.endpoint + url, body, httpOptions)
        .pipe(map(this.parseData))
        .pipe(catchError(this.handleError));
    }

loginService.ts

login(data) {
        return this.httpClient.post('api/authenticate', data , {
            'Content-Type': 'application/x-www-form-urlencoded'
        });
    }

login.ts

onSubmit() {
        if(this.loginForm.invalid) {
            return;
        }else{
            let data = {
                'email': this.loginForm.value.email,
                'password': this.loginForm.value.password
            }
            this.loginService.login(data).subscribe(
                response => {

console.log(response.userInfo.name);

                this.myRoute.navigate(['dashboard']);
            },
            error =>{
                console.log(error);
            }
        )
    }
}

我收到錯誤消息Property 'userInfo' does not exist on type 'Response'. 但在我的http響應中,我是{"status":true,"userInfo":{"id":1,"email":"admin@admin","password":"123456","type":"admin","name":"Admin"},"message":"su"}

我什至不願意刪除我的地圖功能,但訂閱功能仍然遇到相同的錯誤。 Angular 2我沒有遇到這種問題。 發布更新到angular 6我遇到了這個問題,甚至更新了import { map, catchError, tap } from 'rxjs/operators'; 導入文件。

對不起英語不好。 任何更新或見解表示贊賞。 謝謝

您可以使用response['userInfo']默認響應沒有名為userInfo的屬性,您可以將響應類型強制轉換為給定類型或執行上述操作。

如果我從問題中正確猜出,則在編譯時會引發錯誤。 您是否正確定義了響應類型? 它看起來像

type Response = {
  status: boolean,
  userInfo: {id: number, email: string, password: number, type: string, name: string},
  message: string};

或者,如果您打算將post()函數用於其他類型的請求,請在服務中定義一個更通用的post函數,如下所示:

post(url, body, options): Observable<any> { ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM