2017-07-03 4 views
1

私はAngularを初めて使っているので、私が達成しようとしていることについて自分の質問をどのように形成するのかがわかりません。角2 - データの単一の記録を見る

サービスから単一のユーザーレコードを取得しているコンポーネントがあります。それらのユーザーの詳細を自分のUIに表示する必要があります。私のコードの他の部分では、それらは常に複数のレコードになっていましたので、私は*ngForを使用し、データ配列をループしました。しかし、これは単なる結果に過ぎないので、私はこれをどうやって達成するかについてはあまりよく分かりません。

コンポーネント:

import { Component, OnInit } from '@angular/core'; 
import { Router, ActivatedRoute, Params } from '@angular/router'; 
import { UserRecord } from '../shared/user-record.interface'; 
import { UserService } from '../shared/user.service'; 

@Component({ 
    selector: 'app-view-record', 
    templateUrl: './view-record.component.html', 
    styleUrls: ['./view-record.component.css'] 
}) 
export class ViewRecordComponent implements OnInit { 

    private record: UserRecord[]; 
    private errorMessage: any = ''; 
    private loaded = false; 
    private RecordID: number; // User ID of who we are looking at 

    constructor(private _crudService: UserService, 
     private activatedRoute: ActivatedRoute) { } 

    ngOnInit() { 

     // Get the userID from the activated route 
     this.activatedRoute.params.subscribe((params: Params) => { 
      this.RecordID = params['id']; 
     }); 

     // Call our service and pass the userID 
     this._crudService.getRecord(this.RecordID) 
      .then(res => { 
       this.record = this._crudService.record; 
       return this._crudService.getRecord(this.RecordID); 
      }) 
      .then(res => { 
       console.log(this.record) 
       this.loaded = true; 
      }) 
      .catch(err => { console.error(err); }); 
    } 

} 

サービス:

getRecord(userID: number) { 

     const headers: Headers = new Headers({ 
      "Authorization": this._frameworkService.getSessionInfo().token 
     }); 
     return new Promise((resolve, rejects) => { 
      this._http.post(this.baseUrl + '/fetchRecord', { "userID": userID }, { "headers": headers }) 
       .map(res => res.json()) 
       .subscribe((data) => { 
        if (data) { 
         this.record = data; 
        } 
        resolve(true); 
       }); 
     }); 
    } 

インタフェース:

export interface UserRecord { 
    RecordID: number; 
    QID: string; 
    FavoriteColor?: string; 
    FavoriteNumber?: number; 
    FavoriteActor?: string; 
    MetaInsertUTC: string; 
    MetaUpdateUTC: string; 
    FirstName: string; 
    LastName: string; 
    NTID: string; 
} 

サービス結果:私のコンポーネントのHTMLで

[ 
    { 
     "RecordID":"55", 
     "QID":"Q00019204", 
     "FavoriteColor":"Blue", 
     "FavoriteNumber":"6", 
     "FavoriteActor":"Bob", 
     "MetaInsertUTC":"2017-06-29 18:47:01.750", 
     "MetaUpdateUTC":null, 
     "FirstName":"Jim", 
     "LastName":"Bobs", 
     "NTID":"bobby" 
    } 
] 

、私は{{record.FirstName}}を試みたが、ViewRecordComponent.html:16 ERROR TypeError: Cannot read property 'FirstName' of undefinedのエラーが表示されています。

これはデータ結果のセットではないので、私は*ngForがユースケースにどのように適用されるのか分かりません。

私のコンポーネントはrecordオブジェクトにデータを格納しているので、UIからそのデータにアクセスできるはずです。 console.logには、すべての正しいデータポイントが表示されます。

コンポーネントのHTMLにFirstNameというユーザーをどのように参照しますか?うまくいけば、私は少なくとも正しい道にいる。

答えて

1

あなたの応答はオブジェクトのある配列のようですので、record.FirstNameは存在しませんが、record[0].FirstNameはあります。

ビューには、セーフナビゲーションオペレータまたは*ngIfのいずれかを使用して、DeborahKのような未定義の問題にぶつからないようにしてください。 Observable type error: cannot read property of undefined

角度でHTTPを処理する方法についてさらにちょうどいくつかの提案...私は、次のような何かをするだろう...

getRecord(userID: number) { 
    const headers: Headers = new Headers({ 
     "Authorization": this._frameworkService.getSessionInfo().token 
    }); 
    return this._http.post(this.baseUrl + '/fetchRecord', { "userID": userID }, { "headers": headers }) 
     .toPromise() 
     .then(res => res.json()[0]) // get the object only 
     .catch(err => { console.error(err); }); 
} 

とコンポーネント:

this._crudService.getRecord(this.RecordID) 
    .then(res => { 
     this.record = res; 
    }); 

しかし、それは完全にアップしますあなたに:

0

Httpからのデータの取得は非同期です。これは、ページが最初に表示されるときに、データがまだそこにないことを意味します。

そこには、これを解決するには、いくつかの方法があります。

1つのオプションは使用することです「を?」 (安全なナビゲーション)演算子:{{record?.FirstName}}これは、より良いnullを処理します。詳細については、次のリンクを参照してください。https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths

もう1つの方法は、HTMLコードの周囲に* ngIfを使用することです。 *ngIf='record'

ページが最初に表示されても、そのレコードが設定されていないというエラーは発生しません。データが取得されるとすぐに、バインディングは変更を認識し、UIを適切に更新します。サービスを呼び出すコンポーネントであることを購読

ngOnInit(): void { 
    this._productService.getProducts() 
      .subscribe(products => this.products = products, 
         error => this.errorMessage = <any>error); 
} 

注意:ここ

getProducts(): Observable<IProduct[]> { 
    return this._http.get(this._productUrl) 
     .map((response: Response) => <IProduct[]> response.json()) 
     .catch(this.handleError); 
} 

、そのサービスへの呼び出しである:ここでは

は私のサービスのいずれかの方法がどのように見えるかです、サービス自体ではありません。

+0

私はデータをラップする ''を追加しようとしました。私は '.then(res => {this.loaded = true;})'を使ってcomponetサービスコールでこれをtrueに設定しました。エラーはもはやコンソールにスローされませんが、データポイントも表示されません。私が思う少し進歩。 – SBB

+0

なぜ別のプロパティを使用するのですか?ちょうどあなたの 'レコード'プロパティを確認してください。次に、ロードされたプロパティの設定/クリアについて心配する必要はありません。 – DeborahK

+0

良い点、私はそれを変更しました。エラーがなくなり、なぜそれが表示されないのかを判断しようとしたら、結果セットを使用して遊びます。ヒントをありがとう! – SBB

関連する問題