【问题标题】:Angular 2 http.post() is not sending the requestAngular 2 http.post() 没有发送请求
【发布时间】:2016-07-12 13:09:01
【问题描述】:

当我发出 post 请求时,angular 2 http 不会发送此请求

this.http.post(this.adminUsersControllerRoute, JSON.stringify(user), this.getRequestOptions())

http post 不会发送到服务器,但如果我发出这样的请求

this.http.post(this.adminUsersControllerRoute, JSON.stringify(user), this.getRequestOptions()).subscribe(r=>{});

这是有意的吗?如果是的话,有人可以解释一下为什么吗?或者它是一个错误?

【问题讨论】:

    标签: angular angular2-http


    【解决方案1】:

    由于Http 类的post 方法返回一个可观察对象,您需要订阅它以执行其初始化处理。 Observables 是惰性的。

    您应该观看此视频了解更多详情:

    【讨论】:

    • @Thiery 无法观看视频,因为它仅供会员使用
    【解决方案2】:

    如果要执行调用,则必须订阅返回的 observable。

    另请参阅以下角度文档“Communicating with backend services using HTTP”。

    总是订阅

    HttpClient 方法不会开始其 HTTP 请求,直到您对该方法返回的 observable 调用 subscribe()all HttpClient methods 都是如此。

    AsyncPipe 会自动为您订阅(和退订)。

    所有从 HttpClient 方法返回的 observables 在设计上都是冷的。 HTTP 请求的执行是延迟的,允许您在实际发生任何事情之前使用额外的操作来扩展 observable,例如 tapcatchError

    调用 subscribe(...) 会触发 observable 的执行,并导致 HttpClient 编写 HTTP 请求并将其发送到服务器。

    您可以将这些可观察对象视为实际 HTTP 请求的蓝图

    事实上,每个subscribe() 都会启动一个单独的、独立的 observable 执行。订阅两次会产生两个 HTTP 请求。

    const req = http.get<Heroes>('/api/heroes');
    // 0 requests made - .subscribe() not called.
    req.subscribe();
    // 1 request made.
    req.subscribe();
    // 2 requests made.
    

    【讨论】:

      【解决方案3】:

      Get 方法不需要使用 subscribe 方法,但 post 方法需要使用 subscribe。获取和发布示例代码如下。

      import { Component, OnInit } from '@angular/core'
      import { Http, RequestOptions, Headers } from '@angular/http'
      import 'rxjs/add/operator/map'
      import 'rxjs/add/operator/catch'
      import { Post } from './model/post'
      import { Observable } from "rxjs/Observable";
      
      @Component({
          templateUrl: './test.html',
          selector: 'test'
      })
      export class NgFor implements OnInit {
      
          posts: Observable<Post[]>
          model: Post = new Post()
      
          /**
           *
           */
          constructor(private http: Http) {
      
          }
      
          ngOnInit(){
              this.list()
          }
      
          private list(){
              this.posts = this.http.get("http://localhost:3000/posts").map((val, i) => <Post[]>val.json())
          }
      
          public addNewRecord(){
              let bodyString = JSON.stringify(this.model); // Stringify payload
              let headers      = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
              let options       = new RequestOptions({ headers: headers }); // Create a request option
      
              this.http.post("http://localhost:3000/posts", this.model, options) // ...using post request
                               .map(res => res.json()) // ...and calling .json() on the response to return data
                               .catch((error:any) => Observable.throw(error.json().error || 'Server error')) //...errors if
                               .subscribe();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-08
        • 2015-12-30
        • 2018-05-26
        • 1970-01-01
        相关资源
        最近更新 更多