我有一个聊天服务,其主题类型为布尔型。在我的auth服务首先运行之前,该服务不会运行,因为我在auth服务构造函数中订阅了AngularFire authState。一旦authState更改,它将在authState中获取用户uid,并且我的auth服务具有将uid推送到的Subject。我的聊天服务订阅了这个可观察的uid。一旦获得uid,此代码将运行:
export class ChatService {
searching: Subject<boolean> = new Subject<boolean>();
constructor(
public adb: AngularFireDatabase,
) {
this.searching.next(false)
this.userRef = this.adb.database.ref('users').child(uid)
this.userRef.on('value', snapshot => {
if (snapshot.child('searching').val()) {
this.searching.next(true)
this.connected.next(false)
}
if (snapshot.child('connected').val()) {
this.searching.next(false)
this.connected.next(true)
}
})
}
}
我的聊天组件已在this.chat.searching.asObservable().subscribe(console.log)
这样可以很好地记录更改。尽管如果我在组件HTML的任何位置都有{{chat.searching | async}}
,它将不会显示服务中设置的初始false
值。当它更改为true时(在html和console.log中都将更新),但是当它更改为false时它不会更新组件视图,直到我与视图中的某些内容进行交互为止,尽管组件中的console.log仍记录为false
chat.component.html
<div class="chat">
uid: {{auth.user.uid}}
<br>
searching: {{chat.searching | async}}
</div>
chat.component.ts
import { Component, OnInit, ViewChild, NgZone } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { ChatService } from '../services/chat.service';
import { NgScrollbar } from 'ngx-scrollbar';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.scss']
})
export class ChatComponent implements OnInit {
@ViewChild(NgScrollbar) scrollRef: NgScrollbar;
scrollBar: Subscription
foobar
constructor(
public auth: AuthService,
public chat: ChatService,
) { }
ngOnInit() {
this.chat.searching.asObservable().subscribe(v => {
this.foobar = v
console.log(this.foobar)
})
}
}