Angular Service Calls5

1

I have some doubts and some problems.

I have several components with the same function:

Componente1:
  public headers: Object;
  public params: Object;
    sacarDatos(){
       const url='assets/dato1.json';
       this.service.sacarDatos(url).subscribe(
      data => {
        this.headers = data[0].headers;
        this.params = data[1].params;
      }
    }
    ngOnInit() {
        this.sacarDatos();
    }

Componente2:
  public headers: Object;
  public params: Object;

    sacarDatos(){
      const url='assets/dato2.json';
      this.service.sacarDatos(url).subscribe(
      data => {
        this.headers = data[0].headers;
        this.params = data[1].params;
      }
    }
    ngOnInit() {
        this.sacarDatos();
    }




   service:
          public sacarDatos(url:String):Observable<any>{
    return this.http.get<Object[]>(url);
  }

And so on until 14 ...

The doubt is that if component 1: puts in its header and in its params the data of the function with the url data1 and then goes component 2 and calls the same function, as component 1 is subscribed to that function, will the data change for the data of component 2?

I can not verify this because with the old code it works:

Component:

this.http.get('assets/dato1.json').subscribe(data => {
            this.headers = data[0].headers;
            this.params = data[1].params;

But when I changed the code to the service, it stopped working.

    
asked by EduBw 25.06.2018 в 10:10
source

1 answer

1

Your components do not subscribe to a feature , subscribe to Observable , which is what that function returns.

Each call to that function generates an instance of Observable new, so you will not have two components subscribed to the same observable unless you share it in some way.

    
answered by 25.06.2018 / 10:29
source