Angular 6 http +可观察+跨多个组件的主题

时间:2018-12-14 10:06:00

标签: angular http get observable subscribe

我正在尝试共享服务提供商通过HTTP GET检索的数据。我在http.service中获得了数据:

@Injectable()
export class HttpService {

  constructor(private http: HttpClient) { }

  public getData4(url: string): Observable<Premium[]> {
    return this.http.get<Premium[]>(url);
  }
}

应用的路由为:

<TabsComponent>
  <TablesComponent> 
  <TablesComponent/>
</TabsComponent>

在tabs.component.ts中,我拥有:

 export class TabsComponent implements OnInit {

  myUrl4All = 'http://localhost:8083/RCCT-2.0-SNAPSHOT/rest/v2';
  premiumsO: Premium[] = [];

  constructor(private httpService: HttpService, private entity1Service: Entity1Service) { }

  ngOnInit() {
    this.httpService.getData4(this.myUrl4All).subscribe(data => this.premiumsO = 
    data['premiumList']);
  }
}

在我的tabs.component.html中,我拥有:

<div>
<app-tables-component></app-tables-component>
</div>

还有我的table.component.ts:

export class TablesComponent implements OnInit  {

  constructor() { }

  returnedArray: Premium[] = [];

  ngOnInit(): void {

    this.returnedArray = ?????????
  }

}

我的问题是:现在我有一个http.service,带有一个可观察的对象,但是我想使用订阅从我的tables.component中捕获并显示http中的数据。我应该如何更改代码来做到这一点?

1 个答案:

答案 0 :(得分:2)

一种简单快捷的方法是让您在子组件上使用@Input(记住要从@angular/core导入),

export class TablesComponent implements OnInit  {

  constructor() { }

  @Input()
  returnedArray: Premium[] = [];

  ngOnInit(): void { }
}

,然后在您的父母template.html上传递父母数据,如下所示:

<div>
    <app-tables-component [returnedArray]="premiumsO"></app-tables-component>
</div>

编辑:根据下面的评论

将您的Array添加到您的服务中,使其可观察并订阅。喜欢:

@Injectable()
export class HttpService {
  premiumsO: BehaviorSubject<Premium[]> = new BehaviorSubject<Premium[]>();

  constructor(private http: HttpClient) { }

  public getData4(url: string): void {
    this.http.get<Premium[]>(url).subscribe(data => {
        this.premiumsO.next(data['premiumList']);
    });
  }
}

然后在您的父控制器和子控制器中,像这样订阅premiumsO

export class TablesComponent implements OnInit  {

  constructor(private httpService: HttpService) { }
  private subscription: Subscription;
  returnedArray: Premium[] = [];

  ngOnInit(): void {
       this.subscription = this.httpService.premiumsO.subscribe(data => this.returnedArray =  data);
  }
    ngOnDestroy() {
        this.subscription.unsubscribe().        
    }
}

在父母中做同样的事情。不知道这是否是正确的解决方案,但我会这样做。