我是Angular2/Ionic2中的新成員,嘗試創建Notification類服務,但在理解setTimeout完成後未更新通知消息的原因時遇到困難。所以消息得到的值,但setTimeout後不清除。請查看代碼,並給我挖掘的方式。創建通知Angular2服務
服務代碼:
import {Injectable} from '@angular/core';
@Injectable()
export class NotificationService {
public message: string = "";
public interval: number = 2000;
public type: boolean = true;
constructor() {
}
public manageMessage(message: string, interval: number, type: boolean) {
this.message = message;
this.interval = interval;
this.type = type;
setTimeout(
() => {
this.message = "";
console.log("cleared");
},
this.interval);
return this.message;
}
}
註冊組件代碼:
import { Component } from '@angular/core';
import 'rxjs/Rx';
import { BackandService } from '../../providers/backandService';
import { NotificationService } from '../../providers/notificationService';
@Component({
templateUrl: 'signup.html',
selector: 'page-signup',
})
export class SignupPage {
email:string = '';
firstName:string = '';
lastName:string = '';
signUpPassword: string = '';
confirmPassword: string = '';
message: string = '';
constructor(private backandService:BackandService, private notificationService: NotificationService) {
}
public signUp() {
if (this.signUpPassword != this.confirmPassword){
alert('Passwords should match');
return;
}
var $obs = this.backandService.signup(this.email, this.signUpPassword, this.confirmPassword, this.firstName, this.lastName);
$obs.subscribe(
data => {
this.email = this.signUpPassword = this.confirmPassword = this.firstName = this.lastName = '';
},
err => {
this.backandService.logError(err);
let messageArray : any;
try {
messageArray = JSON.parse(err._body);
} catch (e) {
messageArray = err._body;
}
this.message = this.notificationService.manageMessage(messageArray.error_description, 2000, true);
this.email = this.signUpPassword = this.confirmPassword = this.firstName = this.lastName = '';
},
() => console.log('Finish Auth'));
}
註冊HTML模板代碼形式:
<ion-item>
<ion-label floating>Confirm Password</ion-label>
<ion-input type="password" [value]="confirmPassword" (input)="confirmPassword = $event.target.value"></ion-input>
</ion-item>
<div class="message-box" *ngIf="message">
<p>{{message}}</p>
</div>
<button ion-button (click)="signUp()" color="success">Sign Up</button>
使用了'setInterval',而不是'setTimeout' – Erevald
編輯以setTimeout和執行console.log秀「清除」,但新的空字符串值不能結合到模板。 setTimeout( ()=> { this.message =「」; console.log(「cleared」); }, this.interval); – TroAlex