firebase.service.ts
以下代码是我的angular2应用中的firebase服务。配置文件位于app.module.ts中。我想将设备令牌ID发送到服务器。一切正常,但“this.http.post(....)”部分不起作用。
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import * as firebase from 'firebase';
import { AuthService } from './auth.service';
import { ErrorModel } from '../_models/index';
@Injectable()
export class FirebaseService {
private messaging;
private errors = ErrorModel;
constructor(private authService:AuthService, private http:Http) {
this.messaging = firebase.messaging();
}
request_permission_for_notifications(){
this.messaging.requestPermission().then(()=>{
return firebase.messaging().getToken();
}).then(token=>{
if(this.authService.is_logged_in){
let options = this.authService.get_header();
let api_url = '/api/subscribe-device';
this.http.post(api_url,{token:token},options).map((response:Response)=>response.json());
}else{
console.log({success:false,message:this.errors.not_logged_in_error});
}
}).catch(err=>{
console.log('Unable to get permission to notify.', err);
});
}
}
答案 0 :(得分:0)
request_permission_for_notifications(){
return new Promise<string>((resolve, reject)=>{
this.messaging.requestPermission().then(function(){
return firebase.messaging().getToken();
}).then(function(token){
resolve(token);
}).catch(function(err){
console.log('Unable to get permission to notify.', err);
});
});
}
subscribe_device(token:string){
if(this.authService.is_logged_in()){
let options = this.authService.get_header();
let api_url = '/api/subscribe-device';
return this.http.post(api_url,{token:token},options).map((response:Response)=>response.json());
}else{
console.log({success:false,message:this.errors.not_logged_in_error});
}
}
我使用promise来解析我的令牌,然后我使用新功能“subscribe_token”将我的令牌发布到服务器。