Global variable's value not reflating - ionic 2


#1

Hello,

I have created loginUserId global variable in service provider and after login i will changed that value from login.ts and then after i will go in myaccount.ts and get that value but that variable value is no reflating.

login.ts

import {Component} from '@angular/core';
import {MenuController, NavController, NavParams, ToastController} from 'ionic-angular';
import {BrokerService} from '../../providers/broker-service-rest';
import {WelcomePage} from '../welcome/welcome';
import {shareService} from '../../providers/shareService';

@Component({
    selector: 'page-broker-detail',
    templateUrl: 'login.html',
    providers:[BrokerService, shareService]
})
export class LoginPage {

    LoginDetails = {email:'', password:''};
    broker: any;

    constructor(public menuCtrl: MenuController, public navCtrl: NavController, public navParams: NavParams, public service: BrokerService, public toastCtrl: ToastController, private shareService: shareService) {
        this.broker = this.navParams.data;
        this.service.loginUserId = 2;
        service.findById(1).then(
            broker => this.broker = broker
        );
    }

    loginSubmit() {
        var me = this;
        this.service.login(this.LoginDetails.email,this.LoginDetails.password)
            .then(function(response) {
                var data = response.json();

                if(data.status) {
                    //me.service.loginUserId = data.data.userId;
                    me.shareService.setData();
                    me.enableAuthenticatedMenu();
                    me.navCtrl.setRoot(WelcomePage);
                
                    let toast = me.toastCtrl.create({
                        message: 'You have successfully logged in.',
                        cssClass: 'mytoast',
                        duration: 2000
                    });
                    toast.present(toast);
                } else {
                    let toast = me.toastCtrl.create({
                        message: 'Sorry! You have entered an invalid username or password.',
                        cssClass: 'mytoast',
                        duration: 2000
                    });
                    toast.present(toast);
                }
            });

            setInterval(() => {
                console.log('##'+this.shareService.loginUserId);
            }, 2000);
    }

    enableAuthenticatedMenu() {
      this.menuCtrl.enable(true, 'authenticated');
      this.menuCtrl.enable(false, 'unauthenticated');
    }
}

sharedService.ts

export class shareService {  
 
    loginUserId: string;

    constructor() {
    }
 
    setData() {
        this.loginUserId = "1";
    }

    getData() {
        return this.loginUserId; 
    }
}

my-account.ts

import {Component} from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';
import {BrokerService} from '../../providers/broker-service-rest';
import {shareService} from '../../providers/shareService';

@Component({
    selector: 'page-broker-detail',
    templateUrl: 'my-account.html',
    providers:[BrokerService, shareService]
})
export class MyAccountPage {

    broker: any;

    constructor(public navCtrl: NavController, public navParams: NavParams, public service: BrokerService, private shareService: shareService) {
        this.broker = this.navParams.data;
        
        console.log(this.shareService.getData());

        service.findById(this.shareService.getData()).then(
            broker => this.broker = broker
        );

    }

}


#2

you should import your shareService in app.module.ts, first
and add shareService in providers. i guess it will work well after that.
you can delete providers line from your my-account.ts

nb:
better for you to change shareService.ts file name to login.service.ts, just use global naming format to reduce confusion


#3

I have added shareService but still not working.

import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import {WelcomePage} from '../pages/welcome/welcome';
import {PropertyListPage} from '../pages/property-list/property-list';
import {PropertyDetailPage} from '../pages/property-detail/property-detail';
import {BrokerListPage} from '../pages/broker-list/broker-list';
import {BrokerDetailPage} from '../pages/broker-detail/broker-detail';
import {FavoriteListPage} from '../pages/favorite-list/favorite-list';
import {MyAccountPage} from '../pages/my-account/my-account';
import {LoginPage} from '../pages/login/login';
import {AboutPage} from '../pages/about/about';

import {PropertyService} from "../providers/property-service-mock";
import {BrokerService} from "../providers/broker-service-rest";
import {shareService} from "../providers/shareService";

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    WelcomePage,
    AboutPage,
    PropertyListPage,
    PropertyDetailPage,
    FavoriteListPage,
    BrokerListPage,
    BrokerDetailPage,
    MyAccountPage,
    LoginPage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    WelcomePage,
    AboutPage,
    PropertyListPage,
    PropertyDetailPage,
    FavoriteListPage,
    BrokerListPage,
    BrokerDetailPage,
    MyAccountPage,
    LoginPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    PropertyService,
    BrokerService,
    shareService, 
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}


#4

You must remove all providers stanzas from page components. When they are present, they say “give me a separate instance of this provider for each page”.


#5

you need to add

import { Injectable } from ‘@angular/core’;

on your shareService header
and add…

@Injectable() , directive on that page.

import { Injectable } from '@angular/core';
import 'rxjs/Rx';

@Injectable()
export class shareService {
//your code
}

#6

Still not working :frowning:


#7

can you show me your package.json?


#8
{
  "name": "dreamhouse",
  "version": "0.0.0",
  "author": "Christophe Coenraets",
  "homepage": "http://coenraets.org/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.0.0",
    "@angular/compiler": "4.0.0",
    "@angular/compiler-cli": "4.0.0",
    "@angular/core": "4.0.0",
    "@angular/forms": "4.0.0",
    "@angular/http": "4.0.0",
    "@angular/platform-browser": "4.0.0",
    "@angular/platform-browser-dynamic": "4.0.0",
    "@ionic-native/core": "3.4.2",
    "@ionic-native/splash-screen": "3.4.2",
    "@ionic-native/status-bar": "3.4.2",
    "@ionic/storage": "2.0.1",
    "ionic-angular": "3.0.1",
    "ionicons": "3.0.0",
    "leaflet": "^1.0.3",
    "rxjs": "5.1.1",
    "sw-toolbox": "3.4.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.3.0",
    "typescript": "~2.2.1"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-statusbar",
    "cordova-plugin-console",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [
    "ios",
    {
      "platform": "ios",
      "version": "",
      "locator": "ios"
    }
  ],
  "description": "dreamhouse sample app"
}


#9

hey, hardik, i guess you need to upgrade your ionic version to 3.2.0

the reason is, now you use v.3.0.1 which is unstable

you need to read how to upgrade your version here https://github.com/driftyco/ionic/releases

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';

and add this rxjs scrip in your shareService,
i hope it will work now…


#10

Still not working :frowning:


#11

“Not working” is frustratingly and uselessly vague. Post enough code for somebody to be able to replicate your situation. I have not yet seen an acknowledgement of my original comment about eliminating providers on components.


#12

Hi buddies I have implemented the shared service please implement yr accordingly
src/service/constantservice.ts

import { Injectable } from ‘@angular/core’;
@Injectable()
export class ConstantService {
loginUserId: string;

constructor(){};

setData(data) {
       this.loginUserId = data;
   }

   getData() {
       return this.loginUserId;
   }

}

app.component.ts

import { ConstantService } from ‘…/service/constantservice’;

@Component({
templateUrl: ‘app.html’
})

export class MyApp {

 constructor(public constantServiceData: ConstantService){

/set data to service/
this.constantServiceData.setData(“1”);

}

}


the page u want to get(to get the setted value) it myne is landing.ts

import { ConstantService } from ‘…/…/service/constantservice’;

export class LandingPage {

 constructor(public constantServiceData: ConstantService){

         console.log(this.constantServiceData.getData());

// now out put will be 1

}

}

/**** try this if anything issue we can solve it ***/


#13

Not needed. This goes in the app module.


#14

Thanks a lot pavanraju :slight_smile:

but i need set value from login.ts not directly in app.component.ts so please let me know for the same and also let me if i am in wrong way.

I am totally new in ionic 2 and angular.


#15

You posted some code. Many people made suggestions. You say only “still not working” without describing what changes you have made to the code. How is anybody supposed to help you?


#16

I am going to upload full code on git and provide the link here.


#17

#18

You did not listen to my initial comment. You must remove the providers array from login.ts. It is causing you to get a separate instance of sharedService that is not shared with the rest of the app.


#19

yes, we don’t needed providers in login.ts(or any other page) because we already given declared module.ts, Thank you!.


#20

Hi
remove provider name called shareService in all components except modue.ts

make your shareService like this

import { Injectable } from '@angular/core';

@Injectable()

export class shareService {

loginUserId: string;

constructor(){};

   setData(data) {
	   this.loginUserId = data;
   }

   getData() {
	   return this.loginUserId;
   }
}

login.ts

import {shareService} from '../../providers/shareService';

remove  provider name called "shareService"

constructor( private sService: shareService) {

	
}

/* change   me.shareService.setData() to below format */

if(data.status) {

	me.shareService.setData("2"); 
	
	/*dynamic value pass in any component to set data*/
}

my-account.ts

import {shareService} from '../../providers/shareService';


/* remove  provider name called "shareService"  */

constructor( private sService: shareService) {

		console.log(this.sService.getData());
		
}

module.ts

	import {shareService} from "../providers/shareService";

	providers: [shareService]

if still not works change private to public.all the best:)