Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

431
Visualizações
Angular 2, best practice to load data from a server one time and share results to components

What is the best practice to store (and share) initial values in an Angular 2 application using a service? I have a service that loads much data from a server as resources,configurations and other that are array and objects. I do not want to load this data each time I load a component or when I route to a view, I just want to use these objects and array already loaded when the application starts, and optionally reload if needed. The question is where is the right place to store this values and how to share across components that use the service? Thanks.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Gunter is completely right regarding shared services!

Here are some more details for an HTTP that relies on observables and cached data for next calls:

export class SharedService {
  constructor(private http:Http) {
  }

  getData() {
    if (this.cachedData) {
      return Observable.of(this.cachedData);
    } else {
      return this.http.get(...)
            .map(res => res.json())
            .do((data) => {
              this.cachedData = data;
            });
    }
  }
}
over 4 years ago · Santiago Trujillo Relatório

0

You have to think about shared service and make sure only single instance is shared among components.

shared service and shared object demo

Note:
don't forget to register service in bootstrap function. Observe code deeply. you will get what you want. Routing part is not demonstrated. Surf plunk for further implementation

service.ts

import {Component, Injectable,Input,Output,EventEmitter} from 'angular2/core'
import {Router} from 'angular2/router';
import {Http} from 'angular2/http';


export interface Info {
   name:string;
}

@Injectable()
export class NameService {

  constructor(http:Http;router:Router)
  {
    this.http=http;
    // you can call server resource from here and store it down to any variable. 
  }

  info: Info = { name : "Jack" };
  change(){
    this.info.name = "Jane"; // this.info is shared among components.

  }
} 
over 4 years ago · Santiago Trujillo Relatório

0

The right place is definitely a service. If you add this service as provider at one place only, one instance is shared with the whole application. If you add it to providers on each component, each component gets its own instance - which is what you want to avoid

bootstrap(AppComponent, [HTTP_PROVIDERS, MyService]);
@Component({
  selector: 'some-comp',
  providers: [/* don't add MyService here !! */]})
class MyComponent {}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda