在角度2订阅后未定义的值,但在templateurl它可以显示
问题描述:
我试图从我的服务处理值它返回未定义的值。但奇怪的是,如果我直接访问它的模板,这是工作。在角度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";
}
}
任何答案将高度赞赏...
答
尝试象下面这样:
this.detailprodService.getDetail()
.subscribe(details => {
this.product_rating = details.product_rating;
this.getstars(this.product_rating);
}, error => this.errorMessage = <any>error);
应等待订阅新来处理价值。
+0
谢谢,我相信getstars应该在里面订阅。我正在尝试这样的代码,但方式不对。再次感谢您节省我的时间... –
+0
不客气。 –
你能分享组件代码吗?至少你调用'getstars()'的部分,' – Nikolai
我加了它,它正好在订阅代码下面:) –
变量product_rating应该在组件文件中。 –