Angular,在数组上订阅不起作用 [英] Angular, subscribe on an array is not working
问题描述
我正在执行alert.service.我的服务包含一个名为Alert的模型数组.
I am doing an alert.service. My service is containing an Array of a Model called Alert.
这是alert.service
Here is the alert.service
@Injectable()
export class AlertService {
private queue: Alert[] = new Array<Alert>();
constructor() { }
getInstance() : Observable<Alert[]> {
return of(this.queue);
}
push(type: string, title: string, message: string) {
let alert = new Alert(type, title, message);
this.queue.push(alert);
window.setTimeout(_ => {
this.pop();
},3000);
}
pop() {
this.queue.pop();
}
}
在我的alert.component中,我调用此服务并订阅一个可观察队列:
From my alert.component, I call this service and subscribe to an observable of the queue:
export class AlertComponent implements OnInit {
public alert: string = `
<div class="alert [type]">
<span>[title]</span>
<p>[message]</p>
</div>`;
constructor(private alertService: AlertService) { }
ngOnInit() {
this.alertService.getInstance().subscribe(val => {
console.log(val);
});
}
success() {
this.alertService.push('error', 'ninja', 'hahahahahahah hahhahaha hahah hah');
}
}
在我的模板中,我单击一个触发方法 success()
(称为)的按钮.
In my template, I click on a button that triggers the method success()
(which is called).
但是console.log(val)仅返回一次值.这是实例化我的队列服务数组时的值.
But the console.log(val) returns only once a value. This is the value when my queue service array is being instanciated.
我做错了什么?
感谢您的帮助!
推荐答案
最后,
我管理自己可以在我的阵列上使用一个BehaviorSubject.
I manage myself to user a BehaviorSubject on my array.
@Injectable()
export class AlertService {
private queue: Alert[] = new Array<Alert>();
private behaviorSubjectQueue: BehaviorSubject<Alert[]> = new BehaviorSubject<Alert[]>(this.queue);
constructor() {
}
getInstance() {
return this.behaviorSubjectQueue;
}
push(type: string, title: string, message: string) {
let alert = new Alert(type, title, message);
this.queue.push(alert);
this.behaviorSubjectQueue.next(this.queue);
window.setTimeout(_ => {
this.pop();
},3000);
}
pop() {
this.queue.pop();
this.behaviorSubjectQueue.next(this.queue);
}
}
该组件保持不变,但在每次按下和弹出操作时都会得到通知.
The component stays the same but is notified at every push and pop action.
谢谢大家的帮助!
这篇关于Angular,在数组上订阅不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!