2017-10-14 11 views
0

私はAngular/Typescriptウェブ開発の初心者です。Angular 4ホームモジュールのコンストラクタ内でJsonデータをリクエストしますか?

私はASP.NET Core 2.0とAngular 4を使用してWebサイトを開発しています。データを取得してホームページ(Angularアプリケーションのホームコンポーネント)に表示する必要があります。私はいくつかの例を見てきましたし、彼らはこのような何かをやってお勧め:コンポーネントは、ページがロードされたときに提示された最初の1でないとき

import { Component, Inject } from '@angular/core'; 
import { Http } from '@angular/http'; 
@Component({ 
    selector: 'quotes', 
    templateUrl: './quotes.component.html' 
}) 
export class FetchDataComponent { 
    public quotes: Quote[]; 

    constructor(http: Http, @Inject('BASE_URL') baseUrl: string) { 
     http.get(baseUrl + 'api/quotes/recent').subscribe(result => { 
      this.quotes = result.json() as Quote[]; 
     }, error => console.error(error)); 
    } 
} 

interface Quote { 
    text: string; 
    author: string; 
    timeStamp: Date; 
} 

このコードは正常に動作します。ホームコンポーネントでデータを取得しようとすると、サーバーが異常になり、あらゆる種類の例外がスローされます。まず、それはTaskCancelledExceptionをスローし、さらに要求がスロー:

NodeInvocationException: Prerendering timed out after 30000ms because the boot function in 'ClientApp/dist/main-server' returned a promise that did not resolve or reject. 

私は、私は非常に間違ったものをやっていると仮定していますが、私は私が欲しいものをやっての他の方法を見ていません。

問題のコード(http.get要求)を別の関数に移動しようとしましたが、コンポーネントのロードが完了したときにどのように呼び出すべきかわかりません。

import { Component, Inject } from '@angular/core'; 
import { Http } from '@angular/http'; 
@Component({ 
    selector: 'quotes', 
    templateUrl: './quotes.component.html' 
}) 
export class FetchDataComponent { 
    public quotes: Quote[]; 
    private ht: Http; 
    private url: string; 

    constructor(http: Http, @Inject('BASE_URL') baseUrl: string) { 
     this.ht = http; 
     this.url = baseUrl; 
    } 

    fetchQuotes(): void { 
     this.ht.get(baseUrl + 'api/quotes/recent').subscribe(result => { 
      this.quotes = result.json() as Quote[]; 
     }, error => console.error(error)); 
    } 
} 

interface Quote { 
    text: string; 
    author: string; 
    timeStamp: Date; 
} 

httpイベントは私を助けませんでした。私は(click)=""指示文を使ってすべてを動作させることができますが、明らかに、ユーザがアプリケーションのために何かをクリックして期待どおりに動作させる必要はありません。他の指令もどちらも動作していないようです。

以下

私はコンポーネントのHTMLで持っているコードです:

​​

そう要約するために、私は角度は、ページのロード時にデフォルトで表示されますコンポーネントのデータを取得する方法が必要です。

答えて

1

要約すると、 ページの読み込み時に角度がデフォルトで表示されるコンポーネントのデータを取得する方法が必要です。

これを行うための一般的な方法は、あなたがngOnInit()コールバックメソッドで初期化を行うことができます角度OnInitインタフェースを実装することです。

import { OnInit } from "@angular/core"; 
// ... 
export class FetchDataComponent implements OnInit { 
    ngOnInit() { 
     // do initial data load here 
    } 
} 
関連する問題