我有一个订阅服务中的observable的组件。但订阅不会触发服务内的获取。这是我的服务......
echo
以下是试图利用它的组件代码......
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)
}
我很确定只有一个服务实例正在运行。它出现的唯一位置是组件模块的Providers部分。正在从组件的ngOnChanges调用BuildDefaults()。有什么想法吗?
提前感谢。
答案 0 :(得分:0)
你没有使用&#34; return&#34;在服务中返回response.json()的响应。 还要在组件中添加服务的提供者类。
尝试使用下面的代码段。
Service.ts
@Injectable()
export class MeasureRatingService{
private _ratingURL = 'http://localhost:54255/api/MeasureRating/';
errorMessage: string = '';
constructor(private jsonp: Jsonp, 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", options)
.map((response: Response) => {
return <IMeasure[]>response.json();
})
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || ' error');
}
}
component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Service } from '../shared/services/service';
@Component({
selector: 'measureRatings',
template: require('./measureRating.component.html'),
providers: [Service]
})
export class measureRatingComponent implements OnInit {
constructor(private _MRService: MeasureRatingService,
private _router: Router) {
}
.
.
buildDefaults()
{
this.defaultMeasureNames = [];
this._MRService.getMeasureNames()
.subscribe((data: any) => {
this.defaultMeasureNames = data;
},
error => {this.errorMessage = <any>error},
() => { this.buildDefaultRatingArray() }
);
}
希望这会对你有所帮助。