Pra*_*epb 7 javascript twitter-bootstrap angular
我想在用户保存数据时显示Bootstrap警报.
我的代码如下:
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>
Run Code Online (Sandbox Code Playgroud)
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;
}
});
}
Run Code Online (Sandbox Code Playgroud)
}
我想在POST成功完成后显示警报.
我想我错过了如何将'saveSuccess'变量绑定到html,以便在成功保存完成后可以显示警报.(我是Angular2的新手)
昨晚我没有看到它,可能为时已晚.但是您的问题是没有this在您设置的内联函数中使用上下文saveSuccess.
我建议你使用lambdas或"胖箭功能".代替
function(data) { ... }
Run Code Online (Sandbox Code Playgroud)
你做
(data) => { ... }
Run Code Online (Sandbox Code Playgroud)
这样this就可以保留上下文.只需在任何需要内联功能的地方使用它,您就不会有任何问题了!:)
你的代码与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;
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15565 次 |
| 最近记录: |