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



调用组件:

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

删除服务寄存器内的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 s,假设此父组件是AppComponent

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

相关内容

  • 没有找到相关文章

最新更新