簡體   English   中英

Angular 2 http.post() 沒有發送請求

[英]Angular 2 http.post() is not sending the request

當我發出帖子請求時,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=>{});

這是有意的,如果是的話,有人可以解釋我為什么嗎? 或者它是一個錯誤?

由於Http類的post方法返回一個 observable,因此您需要訂閱它以執行其初始化處理。 Observable 是惰性的。

您應該查看此視頻以了解更多詳細信息:

如果要執行調用,則必須訂閱返回的 observable。

另請參閱以下角度文檔“使用 HTTP 與后端服務通信”。

永遠訂閱

HttpClient方法不會開始其 HTTP 請求,直到您對該方法返回的 observable 調用subscribe() 這適用於所有HttpClient方法

AsyncPipe會自動為您訂閱(和取消訂閱)。

HttpClient方法返回的所有 observable 都是設計的。 HTTP 請求的執行被延遲,允許您在實際發生任何事情之前使用附加操作(例如tapcatchError擴展可觀察catchError

調用subscribe(...)會觸發 observable 的執行,並導致HttpClient組合並將 HTTP 請求發送到服務器。

您可以將這些 observable 視為實際 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.

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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM