【问题标题】:Displaying bootstrap alert using angular2使用 angular2 显示引导警报
【发布时间】:2016-10-20 11:02:49
【问题描述】:

我想在用户保存数据后显示 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 成功完成后显示警报。

我想我错过了如何将“saveSuccess”变量绑定到 html,以便在成功保存完成时显示警报。 (我是 Angular2 的新手)

【问题讨论】:

  • 对我来说看起来不错 - 什么不起作用?控制台有错误吗?
  • 没有错误。我认为它不会出错。随着“saveSuccess”变量的更新,将显示“div”。
  • @Pradeepb 这种方法对我不起作用。如果可能的话,你能分享一下 plunker 吗?
  • 对不起,我现在没有任何与此相关的工作代码。
  • @Pradeepb 我做了和你在这里做的一样的事情。我没有错误,并且始终显示警报框。有什么想法吗?

标签: javascript twitter-bootstrap angular


【解决方案1】:

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

我建议您使用 lambdas 或“胖箭头函数”。而不是

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

【讨论】:

【解决方案2】:

考虑这个动态警报组件:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 2018-04-06
    • 2020-07-28
    • 2023-03-12
    • 1970-01-01
    • 2020-12-07
    相关资源
    最近更新 更多