Reputation: 53
I tried to process value from my service it return undefined value. But strangely if i access it directly to template, it was work.
this is my service
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());
}
}
and in component, in onInit method i put
this.detailprodService.getDetail()
.subscribe(details => this.product_rating = details.product_rating,
error => this.errorMessage = <any>error);
this.getstars(this.product_rating);
then if in HTML i put {{product_rating}} it shows the output. but if i process it further in component, it resulted undefined value. i sent product_rating to method 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";
}
}
any answers will be highly appreciated ...
Upvotes: 0
Views: 1724
Reputation: 2582
try like below:
this.detailprodService.getDetail()
.subscribe(details => {
this.product_rating = details.product_rating;
this.getstars(this.product_rating);
}, error => this.errorMessage = <any>error);
you should wait for subscribtion to process the value.
Upvotes: 1