我試圖從我的服務處理值它返回未定義的值。但奇怪的是,如果我直接訪問它的模板,這是工作。在角度2訂閱後未定義的值,但在templateurl它可以顯示
這是我的服務
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import {Globals} from "../globals";
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import {DetailprodComponent} from './detailprod.component';
import {Home} from '../home/home';
import { ActivatedRoute,Router } from '@angular/router';
@Injectable()
export class DetailprodService {
private id:string;
constructor (private http: Http, private route: ActivatedRoute) {
this.route.params.subscribe(params => {let id = params['id'];this.id = id;});
}
getDetail(){
return this.http.get(Globals.server+'/product/'+this.id)
.map(res=> res.json());
}
}
和部件,在OnInit方法我把
this.detailprodService.getDetail()
.subscribe(details => this.product_rating = details.product_rating,
error => this.errorMessage = <any>error);
this.getstars(this.product_rating);
然後如果在HTML我把{{product_rating}}它顯示的輸出。但如果我在組件中進一步處理它,它會導致未定義的值。我送product_rating到方法this.getstars(this.product_rating)
getstars(x){
alert(x)
if (x == 2){
alert("1");
this.starspath ="imagemanagement/1stars.png";
}else if (x == 4){
alert("2");
this.starspath ="imagemanagement/2stars.png";
}else if (x == 6){
alert("3");
this.starspath ="imagemanagement/3stars.png";
}else if (x == 7){
alert("4");
this.starspath ="imagemanagement/4stars.png";
}else if (x == 10){
alert("5");
this.starspath ="imagemanagement/5stars.png";
}
}
任何答案將高度讚賞...
你能分享組件代碼嗎?至少你調用'getstars()'的部分,' – Nikolai
我加了它,它正好在訂閱代碼下面:) –
變量product_rating應該在組件文件中。 –