【发布时间】:2017-04-28 23:10:50
【问题描述】:
我在 angular2 工作,我想向服务器发送 POST 请求。
请建议我如何发送请求?
提前致谢
【问题讨论】:
-
您可以结帐:stackoverflow.com/questions/41033895/… 我刚刚让它为 fcm 服务器工作
我在 angular2 工作,我想向服务器发送 POST 请求。
请建议我如何发送请求?
提前致谢
【问题讨论】:
实际使用的代码可以是:
import { Http, Headers, RequestOptions } from '@angular/http';
......
constructor(public http: Http) { }
sendPushNotification(deviceId: string) {
let url = 'https://fcm.googleapis.com/fcm/send';
let body =
{
"notification": {
"title": "Notification title",
"body": "Notification body",
"sound": "default",
"click_action": "FCM_PLUGIN_ACTIVITY",
"icon": "fcm_push_icon"
},
"data": {
"hello": "This is a Firebase Cloud Messagin hbhj g Device Gr new v Message!",
},
"to": "device token"
};
let headers: Headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'key='+this.someKey
});
let options = new RequestOptions({ headers: headers });
console.log(JSON.stringify(headers));
this.http.post(url, body, headers).map(response => {
return response;
}).subscribe(data => {
//post doesn't fire if it doesn't get subscribed to
console.log(data);
});
}
【讨论】:
声明 ApiService 以发布到 api
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ApiService {
constructor(private http: Http) {
console.log('ApiService init');
}
postSample() {
let param = { val1:'test'};
return this.http.post('http://sample.com',
param
).map(res => res.json());
}
}
在打字稿中使用
this.ApiService.postSample().subscribe(data => {
console.log(data);
});
【讨论】: