首先,我是角度2的新手。我试图在单一服务中调用两个不同的API。但它不会返回任何价值的第二个API' getCityById'但API' getCities'返回值。
这是我的代码:
import { Injectable } from '@angular/core';
import { Http, Headers,Response} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { Cities } from './cities';
@Injectable()
export class CitiesService {
private CityListUrl = "APIurl";
private CityUrl = "APIurl2";
constructor(private http: Http) {}
getCities(): Observable<Cities[]> {
const headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET,PUT,POST,OPTIONS');
headers.append('Access-Control-Allow-Origin', '*');
return this.http.get(this.CityListUrl,{headers: headers})
.map(this.extractData)
.catch(this.handleError);
}
getCityById(CityId:Number): Observable<any> {
const headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET,PUT,POST,OPTIONS');
headers.append('Access-Control-Allow-Origin', '*');
var params = 'cityid='+CityId;
console.log("____________"+this.CityUrl);
console.log(this.http.post(this.CityUrl,params,{headers: headers})
.map(this.extractData));
return this.http.post(this.CityUrl,params,{headers: headers})
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
console.log(res);
let Cities = res.json();
return Cities || { };
}
private handleError(error: Response) {
console.log(error);
return Observable.throw(error.json().error || "500 internal server error");
}
}
我不确定我错了什么。请帮助解决这个问题。