AsyncPipe与BehaviorSubject一起使用,但是我不想用空数据初始化我的服务,因此我使用Subject intead。
问题是NgFor和asyncPipe无法与Subject一起使用,这是一个问题吗?
这有效:
零件:
export class AppComponent {
foo = new BehaviorSubject<Array<number>>([1,2,3]);
getFoo(){
return this.foo.asObservable();
}
}
Run Code Online (Sandbox Code Playgroud)
模板
<span *ngFor="let e of foo.asObservable() | async">{{e}}</span>
Run Code Online (Sandbox Code Playgroud)
这不起作用:
零件
export class AppComponent {
foo = new Subject<Array<number>>();
constructor(){
setTimeout(() => {
this.foo.next([1,2,3]);
}, 3000);
}
getFoo(){
return this.foo.asObservable();
}
}
Run Code Online (Sandbox Code Playgroud)
模板
<span *ngFor="let e of foo.getFoo() | async">{{e}}</span>
Run Code Online (Sandbox Code Playgroud) rxjs subject-observer behaviorsubject angular2-template angular
我已经在我的service.ts中定义了主题
,onEditItem()
其中detail.component.ts
传递了 id 的值,并且在new.component.ts.next()
中订阅了主题
,但订阅不起作用。订阅是在new.component.ts 中完成的ngOnInit
id 值传入成功,onEditItem()
但订阅失败。我尝试在订阅内进行 console.log 检查。但控制台中没有打印任何内容。
在details.component.html中
<a class="btn btn-primary" (click)="onEditItem()" routerLink="/new">Edit</a>
Run Code Online (Sandbox Code Playgroud)
在详细信息.component.ts中
onEditItem(){this.contactService.startedEditing.next(this.id);}
Run Code Online (Sandbox Code Playgroud)
在contactService.ts中
export class ContactService {
startedEditing =new Subject<number>();
}
Run Code Online (Sandbox Code Playgroud)
在new.component.ts中
ngOnInit() {
this.subscription = this.contactService.startedEditing.subscribe(
(index: number) => {
console.log(index);
this.editedItemIndex = index;
console.log(this.editedItemIndex);
this.editMode = true;
this.editedItem = this.contactService.getContacts(index);
this.editForm.setValue({
name: this.editedItem.name,
address: this.editedItem.address
})
}
);
}
Run Code Online (Sandbox Code Playgroud)
我预计中定义的表单new.component.html
应使用详细信息组件中的值进行初始化,但订阅在 中不起作用ngOnInit
。
observable subject-observer behaviorsubject angular2-observables angular
我想创建一个可用于表示动态计算值的类,另一个表示值的类可以是这些动态计算值的源(主题).目标是当主题发生变化时,计算出的值会自动更新.
在我看来,使用IObservable/IObserver是可行的方法.不幸的是我无法使用Reactive Extensions库,因此我不得不从头开始实现主题/观察者模式.
够了blabla,这是我的课程:
public class Notifier<T> : IObservable<T>
{
public Notifier();
public IDisposable Subscribe(IObserver<T> observer);
public void Subscribe(Action<T> action);
public void Notify(T subject);
public void EndTransmission();
}
public class Observer<T> : IObserver<T>, IDisposable
{
public Observer(Action<T> action);
public void Subscribe(Notifier<T> tracker);
public void Unsubscribe();
public void OnCompleted();
public void OnError(Exception error);
public void OnNext(T value);
public void Dispose();
}
public class ObservableValue<T> : Notifier<T>
{
public T Get();
public void Set(T x);
}
public class ComputedValue<T>
{
public T …
Run Code Online (Sandbox Code Playgroud) 无法弄清楚如何根据条件语句订阅 Angular 服务所需的方法
// this.someService.someMethod depending on the conditional statement
.pipe(takeUntil(this.unsubscribe$))
.subscribe((items) => {
this.someData = items;
});
Run Code Online (Sandbox Code Playgroud) 这是在 ngrx 中获取当前状态的解决方案。这个例子很简单——你只需使用take(1)
. 但是在 rxjs 文档中take
它说:
从可观察序列的开头返回指定数量的连续元素
为什么取第一个值会得到当前状态(即最后一个值)?
此外,我在使用Subject
.
在我返回的服务方法中Observable
,我试图通过Subject
已完成的操作通知组件.
completed: Subject<boolean>
constructor(private http: Http) {
}
loadItems(): Observable<FrontItemDto[]> {
return this.http.get ( `${ServiceSettings.ApiUrl}/front` )
.map ( res => {
res.json ();
if ( res.json () ) {
this.completed.next ( true );
}
} )
.catch ( (error: any) => Observable.throw ( error.json ().error || 'Server error' ) );
}
Run Code Online (Sandbox Code Playgroud)
这是组件监听的方式Subject
:
ngOnInit(): void {
this.getItems();
this.sub = this.dataService.completed.subscribe(completed => {
if (completed) {
this.show = false;
}
});
}
Run Code Online (Sandbox Code Playgroud)
但我收到的错误是主题(已完成)未定义.我做错了什么?
根据Subject 的文档,这是Observable的一个特例,它让所有观察者共享一个共同的执行路径。该示例显示每个观察者在订阅源后获得相同的发射值。
我并不完全清楚它与计划Observable发射值的情况有何不同。多个订阅者中的每一个都将收到每个下一个ed 值。在相应订阅之前发出的值不会被传递(除非我们在某些shareReply中明确地使用管道“ed ”)。
使Subject成为Observable的特例的实际区别是什么?我错过了明显的,可能。
我使用共享服务在两个独立组件之间传递数据。当我在共享服务中使用主题时,我无法在订阅组件的html中看到订阅的数据,但订阅后可以在控制台中看到它。而如果我使用Behaviorsubject,效果很好。谁能给我解释一下原因。
共享服务.ts:
//code with subject (not working)
private msgStatistics = new Subject<any>();
msgStatistics$ = this.msgStatistics.asObservable();
msgStats(message) {
this.msgStatistics.next(message)
}
//code with BehaviorSubject (working)
private msgStatistics = new BehaviorSubject<Object>(null);
msgStatistics$ = this.msgStatistics.asObservable();
msgStats(message) {
this.msgStatistics.next(message)
}
Run Code Online (Sandbox Code Playgroud)
组件2.ts:
this.shared_service.msgStatistics$.subscribe(res => {
this.message = res
console.log(this.message)
})
Run Code Online (Sandbox Code Playgroud)
上面的控制台在这两种情况下都会打印消息的值,但它不会以 html 形式呈现主题。
我正在运行RxJava并创建一个使用onNext()
方法来生成数据的主题.我正在使用Spring.
这是我的设置:
@Component
public class SubjectObserver {
private SerializedSubject<SomeObj, SomeObj> safeSource;
public SubjectObserver() {
safeSource = PublishSubject.<SomeObj>create().toSerialized();
**safeSource.subscribeOn(<my taskthreadExecutor>);**
**safeSource.observeOn(<my taskthreadExecutor>);**
safeSource.subscribe(new Subscriber<AsyncRemoteRequest>() {
@Override
public void onNext(AsyncRemoteRequest asyncRemoteRequest) {
LOGGER.debug("{} invoked.", Thread.currentThread().getName());
doSomething();
}
}
}
public void publish(SomeObj myObj) {
safeSource.onNext(myObj);
}
}
Run Code Online (Sandbox Code Playgroud)
在RxJava流上生成新数据的方式是通过@Autowire private SubjectObserver subjectObserver
然后调用subjectObserver.publish(newDataObjGenerated)
无论我为subscribeOn()
&指定什么observeOn()
:
其中onNext()
的实际工作是在实际调用onNext()
主题以生成/生成数据的同一线程上完成的.
它是否正确?如果是这样,我错过了什么?我期待在doSomething()
不同的线程上完成.
更新
在我的调用类中,如果我改变了调用publish
方法的方式,那么当然会为订阅者分配一个新线程来运行.
taskExecutor.execute(() -> subjectObserver.publish(newlyGeneratedObj)); …
Run Code Online (Sandbox Code Playgroud) 我有一个名为BookService的服务项目。
private books: Subject<Book[]>;
getBookList(skip:number = 0,limit:number = 0): Subject<Book[]> {
return this.books;
}
addBookToList(book:Book) {
}
Run Code Online (Sandbox Code Playgroud)
此服务可帮助我监视书籍列表中的更改,我还希望能够使用addBookToList函数将单个书籍添加到列表中,但是我不知道如何添加可观察到的单个书籍(主题观察者)是否可以添加一本书
我正在构建一个过滤器,您可以在其中按类别过滤,您可以通过单击类别名称旁边的复选框来选择一个类别。
所以我有一个filterComponent
,它包含它自己的过滤器,然后是一个filterService
,它有一个类别属性Subject<Array<ICategory>>
,这个属性用于将数据传递到productsComponent
我订阅类别属性的位置。
当我想使用此模式传递一个简单的字符串时,此逻辑有效,但当我想传递对象数组时,它似乎不起作用。
在我的 filters.component.html 文件中,当复选框值发生变化时,我正在调用一个方法:
<li *ngFor="let category of categories">
<mat-checkbox (change)="addOrRemoveCategory(category)" [(ngModel)]="category.isChecked">
{{'category.' + category.Name | translate}}
</mat-checkbox>
</li>
Run Code Online (Sandbox Code Playgroud)
addOrRemoveCategory 方法实现如下所示:
private addOrRemoveCategory(category: ICategory): void {
if (!this.chosenCategories.includes(category)) {
this.add(category);
} else {
this.remove(category);
}
this.filterService.categories.next(this.chosenCategories);
}
Run Code Online (Sandbox Code Playgroud)
所以无论一个类别发生了什么,被添加或删除,(我在内部修改了selectedCategories数组,我用它的值调用 .next() ),我用更新的数组调用 .next() 。
问题是,当selectedCategories数组为空时,我推送到它,并用它调用 .next() 时,我正确地获取了订阅者函数中的值,但是如果再次执行此操作,并且我有一个2 个元素数组,我调用 .next(this.chosenCategories),我的订阅者方法没有收到通知。
但是,一旦我使用空数组调用 .next() ,我的订阅者方法就会再次收到通知(因为我已经删除了之前选择的所有类别)。
订阅者方法:
this.categoriesChangeSubscription = this.filterService.categories
.pipe(
debounceTime(500),
distinctUntilChanged()
)
.subscribe((categories: Array<ICategory>) => { …
Run Code Online (Sandbox Code Playgroud) subject-observer ×11
angular ×8
rxjs ×6
observable ×2
angular6 ×1
c# ×1
ngrx ×1
observers ×1
rx-java ×1
spring ×1
subject ×1
typescript ×1