[英]Angular 2, Observable : http.post, http.get
我對Observables的Http.post和Http.get有一些問題。 我是一名學生,正在嘗試編寫一個簡單的WebApp和一台服務器。
如果我按下按鈕,我想在服務器上發布布爾值。 發布過程確實有效,但是每次我按下按鈕時,我都會再次訂閱可觀察的內容。 我的http.get方法遇到相同的問題,並使用此代碼解決了該問題。
getdata() {
if(this.subscribtion2 === null){
this.isValid = false;
this.subscribtion2 = this.service.get2().subscribe(
daten => {
this.jsonobj = daten;
this.message =
[
this.jsonobj.data.message1,
];
console.log('subscribe')
;
this.myModelneu = this.message[0];
},
err => this.handleError(err),
() => console.log('Simple GET completed')
);
}else
{
this.isValid = true;
console.log('unsubscribe')
this.subscribtion2.unsubscribe();
this.subscribtion2 = null;
}
}
get2()方法在另一個類中。
get2() {
return Observable.interval(3000)
.switchMap(() => this.http.get('http://127.0.0.1:3000/daten/2'))
.map(res => res.json())
}
我不認為這是常見的方法,但我找不到其他方法。 我的http.post看起來像這樣:
post(json: boolean) {
console.log('post executed');
console.log(JSON.stringify(json));
return this.http.post('http://127.0.0.1:3000/login', { json })
.subscribe();
}
我試圖了解Observables的教程,但沒有找到如何在不訂閱Observable的情況下將數據發布到服務器上的方法。
謝謝你的幫助!
http
調用(特別是get
和post
返回一個可觀察到的結果,該結果可完成,因此您無需取消訂閱。 完成后,訂閱將終止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.