Veera
Veera

Reputation: 407

Angular 2 Service not returning value assigned

I am using service for sending data from a component to other.

My service follows

import {
    Injectable
} from '@angular/core';

@Injectable()
export class HomeService {
    values = new Array();

    setValues(values): void {
        this.values = values;
    }

    getValues(): any[] {
        return this.values;
    }
}

Setting value in a component

setType(type) {
  this.values["plan"] = "HMO";
  this.homeService.setValues(this.values);
}

Getting value in other

ngOnInit() {
  this.homeValues = this.homeService.getValues();   
  console.log(this.homeValues);
} 

Above console printing [], how to get assigned values from service?

Upvotes: 0

Views: 532

Answers (2)

Mahmoud
Mahmoud

Reputation: 936

You must use Observable

@Injectable()
export class HomeService {
    values:Observable<any> = [];

    setValues(values): void {
        this.values.next(value);
    }

    getValues(): Observable<any> {
        return this.values.getValue();
    }
}

and in your component, you use

ngOnInit() {
  this.homeService.values.subscribe(v => this.homeValues = v );   

} 

Upvotes: 4

Venomy
Venomy

Reputation: 2244

You are doing something wrong with this.values["plan"] = "HMO";.

This line would make and object like {plan:'HMO'}

So when you set this value to your service it does not save an array as you would expect.

Getting this value in turn would then return an empty array.

First change you could do is to type the setValues

 setValues(values:any[]): void {
        this.values = values;
 }

Secondly you have to change the first line I mentioned to actually make an array.

For example:

this.values = ["HMO"];

Upvotes: 0

Related Questions