Angular, subscribe on an array is not working

十年热恋 提交于 2019-12-11 08:02:18

问题


I am doing an alert.service. My service is containing an Array of a Model called Alert.

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();
  }
}

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');
  }

}

In my template, I click on a button that triggers the method success() (which is called).

But the console.log(val) returns only once a value. This is the value when my queue service array is being instanciated.

What did I do wrong?

Thanks for your help!


回答1:


Finally,

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.

Thank you all for your help!



来源:https://stackoverflow.com/questions/48964567/angular-subscribe-on-an-array-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!