[英]Displaying bootstrap alert using angular2
I want to display Bootstrap alert when the user has saved the data. 我想在用户保存数据时显示Bootstrap警报。
my code is as below: 我的代码如下:
html page: html页面:
<div class="alert alert-success" *ngIf="saveSuccess">
<strong>Success!</strong>
</div>
<form #f="ngForm" (submit)="saveUser(f.value)">
/////Some form fields
<button class="form-control btn btn-primary" type="submit">save</button>
</form>
app.component.ts: app.component.ts:
export class UserProfileComponent{
saveSuccess: boolean;
user: IUser;
saveUser(user:IUser) {
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.editUserForm = user;
this._http.post('api/user/'+this._current_user._id, JSON.stringify(this.editUserForm),{
headers: this.headers
}).subscribe(function(data) {
// if the update is successful then set the value to true
// this is getting updated
if (data){
this.saveSuccess = true;
}
else{
this.saveSuccess = false;
}
});
}
} }
I want to display the alert when a successful POST is done. 我想在POST成功完成后显示警报。
I think i am missing how to bind the 'saveSuccess' variable to html so that alert can be displayed when the successful save is done. 我想我错过了如何将'saveSuccess'变量绑定到html,以便在成功保存完成后可以显示警报。 (I am new to Angular2) (我是Angular2的新手)
Last night I didn't see it, it was probably too late. 昨晚我没有看到它,可能为时已晚。 But your problem is not having the this
context in the inline function where you set saveSuccess
. 但是您的问题是在设置saveSuccess
的内联函数中没有this
上下文。
I'd suggest you use lambdas or "fat arrow function". 我建议你使用lambdas或“胖箭功能”。 Instead of 代替
function(data) { ... }
you do 你做
(data) => { ... }
This way the this
context will be preserved. 这样就可以保留this
上下文。 Just use it wherever you need inline function and you will have no problems anymore! 只需在任何需要内联功能的地方使用它,您就不会有任何问题了! :) :)
Your code with the lambda function: 你的代码与lambda函数:
export class UserProfileComponent{
saveSuccess: boolean;
user: IUser;
saveUser(user:IUser) {
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.editUserForm = user;
this._http.post('api/user/'+this._current_user._id, JSON.stringify(this.editUserForm),{
headers: this.headers
})
.map((data: Response) => data.json) // <-- also add this to convert the json to an object
.subscribe((data) => { // <-- here use the lambda
// if the update is successful then set the value to true
// this is getting updated
if (data){
this.saveSuccess = true;
}
else{
this.saveSuccess = false;
}
});
}
}
Consider this dynamic alert component: 考虑这个动态警报组件:
Angular2 Service which create, show and manage it's inner Component? Angular2服务,它创建,显示和管理它的内部组件? How to implement js alert()? 如何实现js alert()?
for example: . 例如: 。
this.alertCtmService.alertOK("Save changes???").subscribe(function (resp) {
console.log("alertCtmService.alertOK.subscribe: resp=" + resp.ok);
this.saveData();
}.bind(this) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.