【发布时间】:2021-11-22 08:41:12
【问题描述】:
(根据建议,我正在编辑我的问题) @Gunnar.B
与 api 连接的服务
@Injectable({
providedIn: 'root'
})
export class ConsolidadoApi {
constructor(private http: HttpClient) { }
getInvestiments(search?: any): Observable<any> {
return this.http.get<any>(`${environment.basePosicaoConsolidada}`);
}
}
此服务(层)为表示层(组件)中的组件公开状态流和接口
@Injectable({
providedIn: 'root'
})
export class CoreService {
constructor(private api: ConsolidadoApi, private state: StateService) { }
public getInvestments$(): Observable<any> {
return this.state.getInvestiments$()
}
public loadInvestments() {
return this.api.getInvestiments()
.pipe(
tap(investPortifolio => this.state.setInvestments(investPortifolio))
);
}
}
此服务负责将转到组件的逻辑
@Injectable({
providedIn: 'root'
})
export class StateService {
private investments$ = new BehaviorSubject<any>(null);
public getInvestiments$() {
return this.investments$.asObservable()
}
public setInvestments(investPortifolio){
this.investments$.next(investPortifolio)
}
}
但是在我的 html 中没有出现来自 api 的数据。
menu.component.ts
export class MenuComponent implements OnInit {
investments$: Observable<any>;
constructor( private coreService : CoreService ) {
this.investments$ = this.coreService.getInvestments$()
}
ngOnInit(): void {
this.coreService.loadInvestments();
console.log(this.coreService.loadInvestments())
}
}
menu.component.html
<div>
test
</div>
<div *ngFor="let investimentPortifolio of investments$ | async;">
{{investimentPortifolio | json}}
</div>
【问题讨论】:
-
这是一个时间问题。看看stackoverflow.com/questions/14220321/…
-
无论如何我建议不要在服务中存储固定属性,而是将值提供为可观察的以及哪些组件可以订阅(可能使用
async pipe)。搜索 behaviorsubject 和 asobservable。 -
我研究了你说的,你知道为什么数据没有出现在屏幕上吗?
-
你需要在 this.coreService.loadInvestMents() 上调用 subscribe
标签: javascript angular typescript rxjs architecture