【发布时间】:2020-08-11 08:41:43
【问题描述】:
用一个简洁的例子编辑了这个问题。我想这会让人们更容易理解。注意这个例子是超级简化的,通常我在不同的组件之间分层,但是对于这个问题就足够了。
拿这个组件。它采用获取的对象的名称和获取下一个对象的按钮。为了获得下一个 REST 请求的值,我知道除了订阅答案之外别无他法,我想要的是像“combineLatest”这样的东西,但对于“未来”,这样我就可以组合最新的流.
import { Component, VERSION, OnInit } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
private readonly PEOPLE_API_ENDPOINT = `https://swapi.dev/api/people/`;
private characterSubject : BehaviorSubject<any> = new BehaviorSubject<any>({name: 'loading'});
private currentCharacter: number = 1;
character$ : Observable<any> = this.characterSubject.asObservable();
constructor(
private http: HttpClient
) {}
ngOnInit() {
this.updateCurrentCharacter();
}
nextCharacter() : void {
this.currentCharacter ++;
this.updateCurrentCharacter();
}
//I would want to avoid subscribing, instead
//I would like some sort of operation to send the stream
//emissions to the subject. As to not break the observable
//chain up until presentation, like the best practices say.
private updateCurrentCharacter() : void {
this.fetchCharacter(this.currentCharacter)
.subscribe(
character => this.characterSubject.next(character)
);
}
private fetchCharacter (id: number) : Observable<any> {
return this.http.get(this.PEOPLE_API_ENDPOINT + `${id}/`);
}
}
<span>{{ character$ | async }} </span>
<button (click)="nextCharacter()">Next character</button>
有没有办法做到这一点?做类似“emitIn(characterSubject)”的事情。我认为没有像这样动态地将源排放添加到源。
【问题讨论】:
-
hm 我不认为我明白 - 视图应该从
currentData或dataRepository获取数据吗? -
如果您想延迟实际订阅时间,您可以使用
publish和connect。这是您要找的东西吗? -
我想我会用一个具体的例子来编辑这个问题。也许会更容易理解。
标签: angular rxjs observable reactive subject