以下是我如何在我的教程應用程序中實現警報服務,但它不起作用。請問有什麼問題?登錄頁面和註冊頁面上的警報消息都沒有工作角度2警報服務
登錄組件
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;
});
}
註冊頁面
Register(){
this.httpService.createUser(this.module)
.subscribe(data => {
this.alertService.success('Registration Successful', true);
this.redirectToLoginPage()
console.log(data);
},
error =>{
this.alertService.error(error);
});
}
提醒服務
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>
你好akiv,我做了同樣的事情,但仍然沒有working.subject.next沒有發射ngonint .. so警報沒有更新。 – user3090790