Search code examples
htmlangulartypescriptangular2-observables

Angular, subscribe on an array is not working


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!


Solution

  • 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!