Angular 2 Http.Post没有发送请求

时间:2016-12-28 03:44:29

标签: javascript angular typescript ecmascript-6

尝试使用一些数据对我的服务器进行简单的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() { }

}




2 个答案:

答案 0 :(得分:12)

Observable是懒惰的,即使你初始化它们也不会被执行。至少有一个订户必须明确地subscribe该observable来监听该流。简而言之:它们只会在您订阅时执行。

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

答案 1 :(得分:2)

确保您订阅了可观察的数据。 RxJS观察者有2个部分,

  • next() - 它推送由angular本身完成的数据。
  • 订阅 - 您需要在组件中从可观察的数据中获取数据。

尝试下面的内容

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