0
Im獲得承諾作爲firebase auth函數的返回,我需要idToken通過API進行授權。 Im使用Observable設置HTTP get req。我得到一個「401未經授權」,當我運行代碼。 我嘗試在getData函數外運行getIdToken,儘管idToken在控制檯中保持「未定義」狀態。HTTP從Firebase獲取API的Angular 4 Id_token
See this image of the console "undefined" message
我怎麼解決這個問題呢?
服務:
import { Component, OnInit, Inject, Injectable } from '@angular/core';
import { HttpHeaders, HttpParams } from '@angular/common/http';
import { HttpModule, Http, Response, RequestOptions } from "@angular/http";
import * as firebase from 'firebase/app'; //Firebase SDK
import { Observable } from "rxjs/Observable";
import 'rxjs/Rx';
import { AngularFireDatabase, FirebaseListObservable } from "angularfire2/database";
import { Params } from "@angular/router/src";
import { Headers } from '@angular/http';
@Injectable()
export class StoriesService implements OnInit {
page: string;
feed: string;
hits: string;
idToken: any;
private stories: any;
private savedObjects: any;
private apiUrl = 'https://dev-api.byrd.news/v1/stories';
constructor(private http: Http) {
console.log("Yo! Stories!")
}
ngOnInit() { }
fireAuth() {
firebase.auth().currentUser.getIdToken(true).then((idToken) => {
this.idToken = idToken;
})
}
getData(page, feed, hits): Observable<any> {
this.fireAuth();
let headers = new Headers();
headers.append('user_token', this.idToken);
let params = new HttpParams()
.set('page', page)
.set('feed', feed)
.set('hits', hits)
//let options = new RequestOptionsArg({headers: headers, params:params});
console.log(this.idToken, headers, params);
return this.http
.get(this.apiUrl, { params, headers })
.map((response: Response) => {
console.log("Breakthrough!")
return response.json() || {};
})
.catch(this.handleError);
}
private handleError(error: Response) {
return Observable.throw(error.statusText);
}
組件:
getStories() : void {
this.storiesService.getData('0', 'latest','6')
.subscribe(data => {
console.log(data);
})
}
}