Angular 2 - 使用相同的服务实例创建多可用组件

时间:2017-05-07 00:25:25

标签: javascript angular angular2-services angular2-components

致电组件:

<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.

您好,我可以在我的代码中看到,我需要使用相同的注入服务多次调用组件,而不是重复get请求,只为所有组件生成一次Get请求

1 个答案:

答案 0 :(得分:1)

第一种方法

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

删除服务注册表中的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();
    }
}

删除服务this.getData()

中的register()

然后在你插入SomeComponent的模板的组件类中,假设这个父组件是AppComponent

.
.
.
export class AppComponent ... {

  constructor (private someService : SomeService) {}

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