使用angular2显示引导程序警报

时间:2016-06-18 20:29:40

标签: 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>

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;
        }
    });
}

}

我想在POST成功完成后显示警告。

我想我错过了如何绑定&#39; saveSuccess&#39;变量为html,以便在成功保存完成后显示警报。 (我是Angular2的新手)

2 个答案:

答案 0 :(得分:5)

昨晚我没有看到它,可能为时已晚。但是您的问题是在设置this的内联函数中没有saveSuccess上下文。

我建议您使用lambdas或&#34;胖箭头功能&#34;。而不是

function(data) { ... }
你做了

(data) => { ... }

这样将保留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;
            }
        });
    }
}

答案 1 :(得分:1)

考虑这个动态警报组件:

Angular2 Service which create, show and manage it's inner Component? How to implement js alert()?

例如:

this.alertCtmService.alertOK("Save changes???").subscribe(function (resp) {
    console.log("alertCtmService.alertOK.subscribe: resp=" + resp.ok);
    this.saveData();
}.bind(this) );

See this Demo here