httpのポストリクエストからデータを取得した後に、メソッドを呼び出す必要があります。
サービス:request.service.TS。
get_categories(number){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
}, error => {
}
);
}
コンポーネント: Categories.TS
search_categories() {
this.get_categories(1);
//I need to call a Method here after get the data from response.json() !! e.g.: send_catagories();
}
に変更した場合のみ動作します。
サービス:request.service.TSに変更した場合のみ動作します。
get_categories(number){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
this.send_catagories(); //here works fine
}, error => {
}
);
}
しかし、コンポーネント内で this.get_categories(1);
を呼び出した後、次のようにメソッド send_catagories()
を呼び出す必要があります。
コンポーネント: カテゴリ.TS
search_categories() {
this.get_categories(1);
this.send_catagories(response);
}
何が間違っているのでしょうか?
get_categories()`メソッドを更新して、合計値を**返すようにします(observableでラップします)。
// Note that .subscribe() is gone and I've added a return.
get_categories(number) {
return this.http.post( url, body, {headers: headers, withCredentials:true})
.map(response => response.json());
}
search_categories()では、
get_categories()`で返されたobservableをサブスクライブすることができます(または、さらにRxJSの演算子を連鎖させて変換し続けることもできます)。
// send_categories() is now called after get_categories().
search_categories() {
this.get_categories(1)
// The .subscribe() method accepts 3 callbacks
.subscribe(
// The 1st callback handles the data emitted by the observable.
// In your case, it's the JSON data extracted from the response.
// That's where you'll find your total property.
(jsonData) => {
this.send_categories(jsonData.total);
},
// The 2nd callback handles errors.
(err) => console.error(err),
// The 3rd callback handles the "complete" event.
() => console.log("observable complete")
);
}
なお、サブスクライブは最後の1回だけです。
コメントでも述べましたが、任意のobservableの.subscribe()
メソッドは、以下のように3つのコールバックを受け付けます。
obs.subscribe(
nextCallback,
errorCallback,
completeCallback
);
これらはこの順番で渡さなければなりません。3つすべてを渡す必要はありません。多くの場合、nextCallback
だけが実装されます。
obs.subscribe(nextCallback);
コールバック関数をget_category(...)パラメータのリストに追加することができます。
例
get_categories(number, callback){
this.http.post( url, body, {headers: headers, withCredentials:true})
.subscribe(
response => {
this.total = response.json();
callback();
}, error => {
}
);
}
そして、このようにget_category(...)を呼べばいいのです。
this.get_category(1, name_of_function);