cha*_*cha 2 rxjs typescript angular
寻找一种使Service在必要时将最新数据馈送给订阅的组件的方法。例如:Component3将更改写入API> Component1和Component2必须获取最新数据。
当前,这两个组件都订阅了服务返回的可观察对象,如果同时渲染这两个组件,则会导致2个API请求。这感觉不对。在我的理解中,应该向这些组件提供数据,而不是单独请求它们。需要明确的是:此服务返回的数据始终在Component1中使用,而Component2是可选呈现的。
这是一些片段,以及对到目前为止我所做的事情的一些描述:
服务通过HTTP从API获取数据。Component1和Component2订阅了Service返回的observable :
import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import 'rxjs/add/operator/map';
@Injectable()
export class GroupService{
constructor(private _http: Http){}
getGroups(){
return this._http.get('/assets/groups.json')
.map((res) => {
return res.json();
});
}
}Run Code Online (Sandbox Code Playgroud)
Component1和Component2在功能上基本相同。这是其中之一:
import { Component } from '@angular/core';
import { router } from '../../app.router';
import { GroupService } from '../../services/group.service';
import { Group } from '../../interfaces/group.interface';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.scss'],
})
export class SidebarComponent
{
router;
groups: Group[];
constructor(private _groupService: GroupService){
this.router = router;
this.getGroups();
}
getGroups(){
this._groupService.getGroups()
.subscribe((groups) => {
this.groups = groups;
});
}
}Run Code Online (Sandbox Code Playgroud)
我个人更喜欢与seidme略有不同的方法:
在其中建立数据流GroupService并在您的组件中使用它。
服务:
import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class GroupService {
private groupSource = new BehaviorSubject<any>({});
public group$: Observable = this.groupSource.asObservable();
constructor(private _http: Http) {}
getGroups() {
this._http.get('/assets/groups.json')
.map((res) => {
return res.json();
})
.subscribe((groups) => this.groupSource.next(groups));
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的组件中,只需执行以下操作:
import { Component, OnInit } from '@angular/core';
import { router } from '../../app.router';
import { GroupService } from '../../services/group.service';
import { Group } from '../../interfaces/group.interface';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.scss'],
})
export class SidebarComponent implements OnInit {
router;
groups: Observable;
constructor(private _groupService: GroupService){
this.router = router;
}
ngOnInit {
this.groups = this._groupService.group$;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在模板中使用async管道:{{ groups | async }}。它将为您订阅(处置)可观察对象。
现在,无论何时GroupService.getGroups()从任何组件调用,其他所有组件都会自动更新。
此外,使用OnInit它比在构造函数中执行操作更可取,请参见Constructor和ngOnInit之间的区别。
| 归档时间: |
|
| 查看次数: |
1390 次 |
| 最近记录: |