user7345776
user7345776

Reputation:

Alert Service in angular 2

Below is how i am implementing alert services in my tutorial application but it is not working. What could be the problem please? None of the alert messages both on the login page and the registration page is working

login component

login(){
    this.authenticateLoginService.login(this.login.email, this.login.password)
       .subscribe(data => {
          this.redirectToLoginPage();
       },
       error => {
          this.alertService.error('Invalid Username or Password');
          this.loading = false;
        });
}

registration page

Register(){
   this.httpService.createUser(this.module)
      .subscribe(data => {
         this.alertService.success('Registration Successful', true);
         this.redirectToLoginPage()
         console.log(data);
       },
       error =>{
         this.alertService.error(error);
       });
}

alert service

import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class AlertService {
    private subject = new Subject<any>();
    private keepAfterNavigationChange = false;

    constructor(private router: Router) {
       // clear alert message on route change
       router.events.subscribe(event => {
       if (event instanceof NavigationStart) {
          if (this.keepAfterNavigationChange) {
              // only keep for a single location change
              this.keepAfterNavigationChange = false;
          } else {
              // clear alert
              this.subject.next();
          }
       }
   });
   }

   success(message: string, keepAfterNavigationChange = false) {
       this.keepAfterNavigationChange = keepAfterNavigationChange;
       this.subject.next({ type: 'success', text: message });
   }

   error(message: string, keepAfterNavigationChange = false) {
        this.keepAfterNavigationChange = keepAfterNavigationChange;
        this.subject.next({ type: 'error', text: message });
   }

   getMessage(): Observable<any> {
        return this.subject.asObservable();
   }
 }

alert.ts

 import { Component, OnInit } from '@angular/core';
 import { AlertService } from '../Services/alert_services';

 @Component({
    selector: 'alert',
    templateUrl: 'alert.html'
 })

 export class AlertComponent {
   message: any;

   constructor(private alertService: AlertService) { }

   ngOnInit() {
      this.alertService.getMessage().subscribe(message => { this.message = message; });
   }
 }

alert.html

 <div *ngIf="message" [ngClass]="{ 'alert': message, 'alert-success': message.type === 'success', 'alert-danger': message.type === 'error' }">{{message.text}}</div>

Upvotes: 1

Views: 15046

Answers (2)

Akiv
Akiv

Reputation: 498

You need to add in your app.component.html like this <div class="col-sm-8 col-sm-offset-2"> <alert></alert> <router-outlet></router-outlet> </div>

Upvotes: 3

mickdev
mickdev

Reputation: 2875

I didn't check the logic of your code, but one obvious thing is that I don't see you provide AlertService. So you have the choice to provide in AppModule or in every component where you use the service. For example :

            import { Component, OnInit } from '@angular/core';

            import { AlertService } from '../Services/alert_services';

            @Component({
                selector: 'alert',
                templateUrl: 'alert.html',
                providers: [AlertService], //add this line
            })

            export class AlertComponent 

           {
            message: any;

            constructor(private alertService: AlertService) { }

            ngOnInit() {
                this.alertService.getMessage().subscribe(message => {         this.message = message; });
            }
        }

Upvotes: 2

Related Questions