我尝试处理我的服务中的值,但它返回未定义的值。但奇怪的是,如果我直接访问模板,它就可以工作。
这是我的服务
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);
您应该等待订阅来处理该值。
关于javascript - 在 Angular 2 中订阅后未定义值,但在 templateurl 中它可以显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40690162/