javascript - 查看未更新 Ionic 2 和 Angular 2 中的变量更改

标签 javascript angular model-view-controller ionic2 ionic2-providers

我是 Angular 2 的新手,所以我可能不明白出了什么问题。但是,我有一个 *ngIf,如果变量为 false,则应该显示按钮,如果变量为 true,则不显示按钮。

但是,一旦我将变量更新为 true,该按钮就不会消失。任何帮助是极大的赞赏。

代码:

HTML

ion-slide>
<h1> Uber Button </h1>
<button ion-button color="dark" *ngIf="!uberSettings?.uberActivated" (click)="userSettings.connectUber()">Activate Uber</button>
</ion-slide>

组件:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { HomePage } from '../home/home';
import { UserSettings} from '../../providers/user-settings'


@Component({
 selector: 'page-setup',
 templateUrl: 'set-up.html'
})

export class SetUpPage {

  constructor(public navCtrl: NavController, private userSettings: UserSettings) {

 }

  goToHome(){
   this.navCtrl.setRoot(HomePage);
 }



}

服务:

declare
var window: any;


@Injectable()
export class UserSettings {

authorizationCode: string;
uberData: any;

uberSettings: UberSettings;
result: any;




constructor(public http: Http, private platform: Platform, public storage: Storage) {

    console.log('called uberSettings Constructor');

    storage.ready().then(() => {

        storage.get('uberSettings').then((val) => {

                console.log('the val is' + val);
                if (val == null) {
                    console.log('val equaled null');
                    this.uberSettings = {
                        buttonOn: false,
                        uberActivated: false,
                        token: null,
                        refreshToken: null,
                        long: null,
                        lat: null,
                    }

                    console.log(this.uberSettings);

                    storage.set('uberSettings', this.uberSettings);

                    // this.uberSettings.uberActivated = true; 
                    // // this.uberSettings.token= val.token;
                } else {
                    console.log("there was a value for Val");
                    this.uberSettings = val
                    console.log(this.uberSettings);
                }
            })

            .catch(err => {
                console.log('we dont have an uber token yet' + JSON.stringify(err));
            });


    });




}

public connectUber() {
    this.platform.ready().then(() => {
        this.uberLogin().then(success => {
            this.authorizationCode = success;
            console.log(this.authorizationCode);
            this.token()

        }, (error) => {
            alert(error);
        });
    });
}


token() {

    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    // let body = 'client_id=3ibytPcye4w3_-0txknyO7ptD-MfFMkn&client_secret=2Kp8O54mGvlOoBm6IPX_0gKBmJ_mODSo7FqPbbA9&redirect_uri=http://localhost:8100/callback&grant_type=authorization_code&code=' + this.authorizationCode

    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('client_id', <CLIENT ID>);
    urlSearchParams.append('client_secret', <CLIENT SECRET>);
    urlSearchParams.append('redirect_uri', 'http://localhost:8100/callback');
    urlSearchParams.append('grant_type', 'authorization_code');
    urlSearchParams.append('code', this.authorizationCode);
    let body = urlSearchParams.toString()


    return this.http.post(`https://login.uber.com/oauth/v2/token`, body, {
            headers: headers
        })
        .map(response => response.json())
        .subscribe(result => {

            this.result = result
            console.log(this.result);
            this.uberSettings.token = this.result.access_token;
            this.uberSettings.refreshToken = this.result.refresh_token;
            this.uberSettings.uberActivated = true;
            this.uberSettings.buttonOn = true;
            console.log(this.uberSettings);

        });

    public uberLogin(): Promise < any > {
        return new Promise(function(resolve, reject) {
            var browserRef = window.cordova.InAppBrowser.open("https://login.uber.com/oauth/v2/authorize?client_id=3ibytPcye4w3_-0txknyO7ptD-MfFMkn&response_type=code", "_blank", "location=no,clearsessioncache=yes,clearcache=yes");
            browserRef.addEventListener("loadstart", (event) => {
                if ((event.url).indexOf("http://localhost:8100/callback") === 0) {
                    browserRef.removeEventListener("exit", (event) => {});
                    browserRef.close();

                    var responseParameters = ((event.url).split("code="));

                    var parsedResponse = responseParameters[1].split("#");

                    if (parsedResponse[0] !== undefined && parsedResponse[0] !== null) {
                        resolve(parsedResponse[0]);
                    } else {
                        reject("Problem authenticating with Uber");

                    }

                }
            });
            browserRef.addEventListener("exit", function(event) {
                reject("The Uber sign in flow was canceled");
            });
        });
    }

}

因此,如果您查看服务代码,我会在调用 token() 时更新 this.uberSettings,并且控制台显示 this.uberSettings.uberActivated 已更改为 true。但是,我不明白为什么该按钮仍然显示。任何帮助将不胜感激。谢谢你!

最佳答案

您的 ngIf 未引用您的服务。我认为你有一个错字:)

*ngIf="!userSettings.uberSettings?.uberActivated" 

而不是

*ngIf="!uberSettings?.uberActivated" 

关于javascript - 查看未更新 Ionic 2 和 Angular 2 中的变量更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43905921/

相关文章:

javascript - 有没有办法在将 .ejs 文件渲染到 .html 文件的同时运行函数?

javascript - 从 JavaScript 中的事件监听器调用访问对象的属性

angular - 如何将额外的参数传递给 Angular 中的异步验证器(响应式(Reactive)表单)?

java - Bean 属性不可读或具有无效的 getter 方法

javascript - 将服务注入(inject) Controller 会引发错误

javascript - fullcalendar.io - 在内存中保存事件

javascript - 使用 AngularFire2 将文件上传到 Firebase 存储

angular - 将可拖动的 div 的一部分设置为不可拖动

php - Joomla:在自定义 View 中保存表单时出错

javascript - Redux 表单向导,发送 json 字段数据的按钮?