简体   繁体   English

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

[英]Angular 2, Observable : http.post, http.get

I have a few problems concerning Http.post and Http.get with Observables. 我对Observables的Http.post和Http.get有一些问题。 I'm a student and I'm trying to write a simple WebApp and a Server. 我是一名学生,正在尝试编写一个简单的WebApp和一台服务器。

I want to post a boolean on my Server if I press a button. 如果我按下按钮,我想在服务器上发布布尔值。 The post process does work but everytime I press the button I subscribe another time to the observable. 发布过程确实有效,但是每次我按下按钮时,我都会再次订阅可观察的内容。 I had the same problem with my http.get method and resolved the problem with this code. 我的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;

   }
}

The get2() method is in a different class. get2()方法在另一个类中。

  get2() {


        return Observable.interval(3000)
          .switchMap(() => this.http.get('http://127.0.0.1:3000/daten/2'))
          .map(res => res.json())

  }

I don't think that is the common way but I can't find another. 我不认为这是常见的方法,但我找不到其他方法。 My http.post look likes this : 我的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();

   } 

I tried to understand the tutorials with Observables but I did not find how to post data on the server without subscribing to the Observable. 我试图了解Observables的教程,但没有找到如何在不订阅Observable的情况下将数据发布到服务器上的方法。

Thanks for your help! 谢谢你的帮助!

The http calls, specifically get and post return an observable that completes with the result, hence you don't need to unsubscribe. http调用(特别是getpost返回一个可观察到的结果,该结果可完成,因此您无需取消订阅。 On completion the subscription is terminated. 完成后,订阅将终止。

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

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