簡體   English   中英

Angular 2 Http.Post沒有發送請求

[英]Angular 2 Http.Post not sending request

嘗試使用一些數據對我的服務器進行簡單的POST,並返回一些JSON數據。 (目前,它通過電話運行,但我在網絡選項卡上看不到它實際上試圖制作它?)

我的服務(api.service.ts)

 import { Injectable } from '@angular/core'; import { Headers, Http, Response} from '@angular/http'; import {Observable} from 'rxjs/Rx'; // Import RxJs required methods import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; @Injectable() export class ApiService { private headers = new Headers({'Content-Type': 'application/json'}); private myUrl = 'https://www.mywebsite.com'; // URL to web api private payLoad = {"thingy1":"Value1", "thingy2":"value2"}; constructor(private http:Http) { } getData () { this.http.post(this.myUrl, JSON.stringify(this.payLoad), this.headers) .map((res:Response) => res.json()) .catch((error:any) => Observable.throw(error.json().error || 'Server error')); } } 

然后我只是在頭組件中運行getData方法來觸發它。 (header.component.ts)

 import { Component, OnInit } from '@angular/core'; //Service import { ApiService } from '../services/api.service'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.scss'] }) export class HeaderComponent implements OnInit { constructor(private service:ApiService) { this.service.getData(); //Fire getData from api.service } ngOnInit() { } } 

Observable是懶惰的,即使你初始化它們也不會被執行。 至少一個訂戶必須顯式subscribe該observable以收聽該流。 簡而言之:它們只會在您訂閱時執行。

this.service.getData().subscribe(
  (data) => console.log(data)
);

確保您訂閱了可觀察的數據。 RxJS觀察員有2個部分,

  • next() - 它推送由angular本身完成的數據。
  • 訂閱 - 您需要在組件中從可觀察的數據中獲取數據。

嘗試以下內容

this.service.getData().subscribe(
  (data) => {
   //process your data here
  }
);

暫無
暫無

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

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