繁体   English   中英

Angular 2,Observable:http.post,http.get

[英]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调用(特别是getpost返回一个可观察到的结果,该结果可完成,因此您无需取消订阅。 完成后,订阅将终止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM