-1

HttpClientを使用してレスポンスObjでHtmlを更新すると、値が更新されますがエラーが発生します。親切に助けて!Httpレスポンスの更新HTMLを取得してもコンソールで未定義のエラーが発生する

ファイル名 - AUTH-service.ts

import { any } from 'codelyzer/util/function'; 
import { Injectable } from '@angular/core'; 
import { HttpClient } from '@angular/common/http'; 

@Injectable() 
export class AuthService { 

    constructor(private httpClient: HttpClient) { } 
    get() { 
    return this.httpClient.get<any>('/capi/v2/users/me', { 
     observe: 'body', 
     responseType: 'json' 
    }); 
    } 
}; 

ファイル名 - dashboard.component.ts

import { AuthService } from './../../services/api/auth-service'; 

import { Component, Injectable, OnInit } from '@angular/core'; 

@Component({ 
    selector: 'app-dashboard', 
    templateUrl: './dashboard.component.html' 
}) 

@Injectable() 
export class DashBoardComponent implements OnInit { 
    user; 
    constructor(private authService: AuthService) {}; 

    ngOnInit() { 
     this.authService.get() 
     .subscribe(
      (response) => { 
       this.user = response; 
      } 
     ); 
    } 
} 

応答objがある -

{

"firstName": "xyz", 
"lastName": "abc", 
"active": true 

}

ファイル名 - dashboard.component.html

<div class="container-fluid text-center"> 
    <h1 class="bold m-t m-b-xs">Hey there!</h1> 
    <h3 class="m-b">How are you doing today?</h3> 


    {{ user.active }} 

    <div class="block clear m-a">&nbsp;</div> 

    <div class="row m-t p-t"> 
     <div class="col-xs-12"> 
     </div> 
    </div> 
</div> 

エラーコンソールenter image description here

+0

アクティブはユーザーの所有物であるようです。 @Injectable()はコンポーネントであり、注射可能ではないため、コンポーネントから削除してください。 – fubbe

+0

まだ解決されていないエラー –

答えて

0

にあなたがコンポーネントへの応答を返すために、マップ機能を使用する必要があります。このコードをあなたのサービスに置き換えてください。

get() { 
    return this.httpClient.get<any>('/capi/v2/users/me') 
    .map((resp) => resp) 
    .catch((error) => error); 
} 
+0

私はコードを変更しましたが、まだエラーが発生しています。 –

+0

さらに、このエラーが発生したマップmを追加した後 - core.es5.js:1020 ERROR TypeError:ストリームが予期されていた場所で無効なオブジェクトを指定しました。 Observable、Promise、Array、またはIterableを提供できます。 –

3

あなたは、単に?を含めるように{{ user.active }}を更新することができます。角度がget要求が完了する前にuser.activeを評価しようとするためすなわち:

{{ user?.active }} 

あなたの誤差がありそうです。

これはsafe navigation operatorとして知られています:あなたが代わりにデータが取得されるまで、あなたのコンテナのレンダリングを避けるためにngIfを使用することができ

The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths.

。すなわち:

<div class="container-fluid text-center" *ngIf="user"> 
関連する問題