Search code examples
javascriptangularangular2-servicesangular2-components

Angular 2 - create multiable components with the same service instance


Calling Components:

<some-component></some-component>
<some-component></some-component>

Component:

@Component ({
  selector : 'some-component',
})

export class SomeComponent implements OnInit {
    constructor (private someService : SomeService) {}

    ngOnInit(): void {
      this.someService.register();
    }
}

Service:

@Injectable()
export class SomeService{
   private targets: Array;
    constructor (private http: Http) {}

    register(){
     this.targets.push('x');
     getData();
    }   

    getData(){
      console.log(targets);
      let params = this.targets.join(); // 'x,x'
      return this.http.get(params);
    }
}

console:

['x']
['x','x']
// what I need to do to whit until the last one and make the get request.

Hello as you can see in my code I need to call a component many times with the same injected service and not to repeat the get request just making the Get request once for all the components


Solution

  • First approach

    import { Input } from '@angular/core';
    
    
    @Component ({
      selector : 'some-component',
    })
    
    export class SomeComponent implements OnInit {
    
        @Input() isLast = false;
    
        constructor (private someService : SomeService) {}
    
        ngOnInit(): void {
          this.someService.register();
          if (this.isLast) {
            this.someService.getData();
          }
        }
    }
    

    Delete the this.getData() inside your service's register()

    Then in the template where you drop SomeComponents in

    <some-component></some-component>
    <some-component></some-component>
    <some-component [isLast]='true'></some-component>
    

    Second approach

    @Component ({
      selector : 'some-component',
    })
    
    export class SomeComponent implements OnInit {
    
        constructor (private someService : SomeService) {}
    
        ngOnInit(): void {
          this.someService.register();
        }
    }
    

    Delete the this.getData() inside your service's register()

    Then inside the component class of the template where you insert your SomeComponents, let's say this parent component is AppComponent

    .
    .
    .
    export class AppComponent ... {
    
      constructor (private someService : SomeService) {}
    
      // import AfterViewInit from angular core package
      ngAfterViewInit(): void {
          this.someService.getData();
      }
    }