gpt4 book ai didi

javascript - 立即创建 Observable 并排队发出直到订阅

转载 作者:行者123 更新时间:2023-12-03 04:50:57 26 4
gpt4 key购买 nike

我有一个消息 Observable,用于在页面上显示通知。我遇到的问题是,在消息组件初始化之前页面加载时发生错误,这意味着 Observable 尚未订阅,因此当我尝试发出错误时未定义。

export class MessageService {
public messagesSource: Observable<IMessage>;
private messagesObserver: any;

constructor() {
console.log('MessageService constructor called');
this.messagesSource = new Observable(observer => {
console.log('MessageService observer called');
this.messagesObserver = observer;
}).share();
}

public show = (message: IMessage) => {
if (this.messagesObserver) {
this.messagesObserver.next(message);
} else {
console.error('this.messagesObserver is not initialised', this.messagesObserver);
}
}
}


export class MessagingComponent {
public messages: IMessage[] = [];

constructor(private messageService: MessageService) {
console.log('messaging component constructor');
this.messageService.messagesSource.subscribe(message => this.setMessage(message));
}
}

// and within my HttpService:
private errorHandler = (error: Response): Observable<any> => {
const err: string = error.text() || JSON.stringify(error);
console.error('App error occurred:', err);
this.messageService.show({ content: err, level: 'danger'});
return Observable.from([null]);
}

正常操作日志:

Navigated to http://localhost:8090/

MessageService constructor called

messaging component constructor

MessageService observer called

Angular is running in the development mode.

当解析器出现错误时:

Navigated to http://localhost:8090/jobs

MessageService constructor called

GET http://localhost:7777/api/jobs 401 (Unauthorized)

App error occurred: Authorization failure, invalid bearer token.

this.messagesObserver is not initialised undefined

messaging component constructor

MessageService observer called

Angular is running in the development mode.

所以我需要一种方法让 new Observable(observer) 立即创建观察者,这样它就不是未定义的,并且当组件准备订阅时消息不会丢失和发出.

最佳答案

您需要创建一个BehaviorSubject ,

Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.

您还可以使用ReplaySubject ,如果您想缓冲所有响应。

希望这有帮助!!

关于javascript - 立即创建 Observable 并排队发出直到订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42658787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com