0

I am new to angular, I have a toast message element in app component, now for every service call from any component i am calling a service to show and pushing message in the array. now the issue is app component is not able to repeat the array and update its value on pushing or deleting any object. Here is my code :-

app component.html :-

<div *ngFor="let toast of toastList">
    <div class="toast">
        <span class="close" (click)="closeToast($event)">&times;</span>
        <div class="loading">Loading data {{toastList.message}}<span>.</span><span>.</span><span>.</span></div>
    </div>
</div>

app component.ts:-

ngOnInit() {
    this.subscription = this.commonService.addObject$.subscribe(toasterArray => this.toastList = toasterArray);
    console.log('subscription is : ' + this.subscription);
}

ngOnDestroy() {
    this.subscription && this.subscription.unsubscribe();
}

closeToast($event) {
    this.commonService.toggleToaster(false, null);
}

service.ts:-

export class CommonService {
    private toastArray: any = [];
    private toasterArray: BehaviorSubject<any> = new BehaviorSubject<any>(this.toastArray);

    addObject$: Observable<number> = this.toasterArray.asObservable();

    constructor() {
    }

    toggleToaster = (action, message) => {
        if (action === true) {
            this.toastArray.push(message);
            this.toasterArray.next(this.toastArray);
        } else if (action === false) {
            this.toastArray = this.toastArray.filter(element => element.message !== message);
            this.toasterArray.next(this.toastArray);
        }

    }
    getToastArray = () => {
        return this.toastArray;
    }
}

component.ts to call the service to show toast :-

getPass() {
    this.membeService.getPass(this.page).subscribe(
        data => {
            let toaster = { "message": this.page.searchParams };
            this.commonService.toggleToaster(true, { 'message': 'get Passenger' });
        },
        err => {
            console.error(err);
        }
    )
};

Help me

ShamPooSham
  • 2,301
  • 2
  • 19
  • 28

1 Answers1

0

You have an ngFor loop using 'toast' variable but are trying to read from 'toastList' in the loop. In the ngFor, change to:

    <div class="loading">Loading data {{toast.message}}<span>.</span><span>.</span>

Instead of toastList.message.

Working StackBlitz example based on your code:

Also you are returning type of number here: addObject$: Observable = this.toasterArray.asObservable();

It may well not matter but try changing from number to any.

JMP
  • 1,864
  • 2
  • 8
  • 16