我试图从我的服务处理值,它返回未定义的值。但是奇怪的是,如果我直接将其访问模板,那是可行的。
这是我的服务
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";
}
}
任何答案将不胜感激...
最佳答案
尝试如下:
您应该等待订阅处理该值。
关于javascript - 订阅 Angular 2后未定义的值,但可以在templateurl中显示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40690162/