0

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?

2 Answers 2

4

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 );   

} 
Sign up to request clarification or add additional context in comments.

2 Comments

I tried like this, coming SelectTypeComponent_Host.html:1 ERROR TypeError: Cannot read property 'subscribe' of undefined
are you import HomeService and defined it in the constructor, like constructor(private homeService:HomeService )
0

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"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.