我有一個組件訂閱服務中的observable。但是訂閱不會觸發服務中的獲取。這裏是我的服務....Angular2 - 訂閱不觸發服務調用
import { Injectable } from '@angular/core';
import { IMeasureRating } from './measureRating';
import { IRating } from './rating';
import { IMeasure } from './measure';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { ErrorHandler } from '../error-handler/error-handler.component';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
declare function require(name: string);
@Injectable(
)
export class MeasureRatingService{
private _ratingURL = 'http://localhost:54255/api/MeasureRating/';
errorMessage: string = '';
constructor(private _http: Http, private _errorHandler: ErrorHandler) {
}
getMeasureNames(): Observable<IMeasure[]> {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
return this._http.get(this._ratingURL + "getMeasureNames", { headers: headers })
.map((response: Response) => <IMeasure[]>response.json())
.do(data => console.log("MR getMeasureNames: " + JSON.stringify(data)))
.catch(this.handleError)
}
,這裏是正在試圖利用它的分量碼...
@Component({
selector: 'measureRatings',
template: require('./measureRating.component.html')
})
.
.
.
export class measureRatingComponent implements OnInit {
.
.
.
constructor(private _MRService: MeasureRatingService, private _router: Router) {
}
.
.
buildDefaults()
{
this.defaultMeasureNames = [];
this._MRService.getMeasureNames()
.subscribe(x => this.defaultMeasureNames = x,
error => this.errorMessage = <any>error,
() => { this.buildDefaultRatingArray() });
}
我敢肯定有唯一的一個實例服務運行。它出現的唯一地方是在組件模塊的提供者部分。 BuildDefaults()從組件的ngOnChanges被調用。有什麼想法嗎?
在此先感謝。
從ngOnInit調用BuildDefaults(),因爲組件的某些數據綁定屬性更改 –