Angular 2 - 创建具有相同服务实例的多组件

Angular 2 - create multiable components with the same service instance

调用组件:

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

分量:

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

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

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

服务:

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

控制台:

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

您好,正如您在我的代码中看到的那样,我需要使用相同的注入服务多次调用一个组件,而不是重复获取请求,只是对所有组件发出一次获取请求

第一种方法

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

删除服务的 register() 中的 this.getData()

然后在模板中放置 SomeComponents

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

第二种方法

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

export class SomeComponent implements OnInit {

    constructor (private someService : SomeService) {}

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

删除服务 register()

中的 this.getData()

然后在您插入 SomeComponent 的模板组件 class 中,假设此父组件是 AppComponent

.
.
.
export class AppComponent ... {

  constructor (private someService : SomeService) {}

  // import AfterViewInit from angular core package
  ngAfterViewInit(): void {
      this.someService.getData();
  }
}