Search code examples
javascriptangularmodel-view-controllerionic2ionic2-providers

View not updating on variable change in Ionic 2 and Angular 2


I'm new to using Angular 2 so I may just not be understanding what's wrong. However, I have an *ngIf that is supposed to show a button if a variable is false and not show the button if the variable is true.

However once I've updated the variable to true, the button does not go away. Any help is greatly appreciated.

Code:

HTML

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

COMPONENT:

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



}

SERVICE:

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

}

So if you look at the service code I am updating this.uberSettings when token() is called and the console shows that this.uberSettings.uberActivated has been changed to true. However, I don't understand why the button still shows then. Any help would be greatly appreciated. Thank you!


Solution

  • Your ngIf is not referencing your service. I think you have a typo :)

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

    instead of

    *ngIf="!uberSettings?.uberActivated"