How to make a variable accessible from different functions in different .ts files?


#1

Hello how is it possible to call a variable from different .ts file in different page inside src code???

For example, i am getting a webapi token from a httppost request in home page and i have a loginPage in which i want to use the webapi token in order to make authentication user.


#2

You can import your other component/provider…

import { OtherComponent } from '../../providers/other/other';

export class CurrentComponent {

  otherToken:any;

  constructor(
    private other: OtherComponent,
  ) { }

this.otherToken = other.SomeFunctionFromOtherThatReturnsToken()

#3

wow it seemed very awesome
but i am getting this error when i am insterting in my constructor

  constructor(
   public navCtrl: NavController, public navParams: NavParams,
   private loginserviceprovider: LoginserviceProvider,
   public other:HomePage) {
  }

image


#4

Can you share more code? It’s hard to understand your issue without more info.


#5

@ src/pages/home.ts

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {LoginserviceProvider} from "../../providers/loginservice/loginservice";
import * as xml2js from 'xml2js';
import {LoginScreenPage} from "../login-screen/login-screen";
import {LoginScreenPageModule} from "../login-screen/login-screen.module";
import {Storage} from "@ionic/storage";

var webApihost="http://192.168.0.6:81/EBSWebApi/";
var scrollerid = "ES00BACKUP/KHCApp_Items";
var scrid = "ES00BACKUP/KHCApp_Contacts";
var commandid = "";
var ScrollerDatasetTest = "";
//let token;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  token:string;
  url: string;
  params: {
    SubscriptionPassword: string;
    model: {
      BranchID: string;
      LangID: string;
      UserID: string;
      Password: string;
    }
  };


  //scroller code below//
  paramsScroller: {
    headers: {
      Authorization: string;
    },
    data: {
      Code: string;
    }
  };
 // Model:string;

  constructor(public navCtrl: NavController,
              private loginserviceprovider: LoginserviceProvider,
              private storage:Storage) {

  }


  ionViewWillEnter() {

    this.url = webApihost + 'api/login';

    this.params = {
      SubscriptionPassword: 'passx',
      model: {
        BranchID: "01",
        LangID: "el-GR",
        UserID: "khcadmin",
        Password: "P@ssw0rd",
      }
    };

    console.log("Token prin" + this.token);
    return this.loginserviceprovider.getWebApi(this.url, this.params)
      .subscribe(data => {
        console.log(data);
        this.token = data.Model.WebApiToken;
        console.log("Μόλις πήρα το Token -> " + this.token);
        this.navCtrl.push(LoginScreenPage);

      });

  };




@ src/pages/login-screen.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {LoginserviceProvider} from "../../providers/loginservice/loginservice";
import {Storage} from "@ionic/storage";
import {HomePage} from "../home/home";


var webApihost="http://192.168.0.6:81/EBSWebApi/";
var scrollerid = "ES00BACKUP/KHCApp_Items";
var scrid = "ES00BACKUP/KHCApp_Contacts";
var commandid = "";
var ScrollerDatasetTest = "";
//var token="";


@IonicPage()
@Component({
  selector: 'page-login-screen',
  templateUrl: 'login-screen.html',
})
export class LoginScreenPage {
  token:any;
  url: string;
  params: {
    SubscriptionPassword: string;
    model: {
      BranchID: string;
      LangID: string;
      UserID: string;
      Password: string;
    }
  };
 

 
  paramsScroller: {
    headers: {
      Authorization: string;
    },
    data: {
      Code: string;
      Mobile1:string;
    }
  };
  constructor(public navCtrl: NavController, public navParams: NavParams,
              private loginserviceprovider: LoginserviceProvider,
              public other:HomePage) {
  }

  scrollerid (){
   this.token=this.other.ionViewWillEnter();
    console.log("ti token exw??? "+this.token);
    this.url = webApihost + "api/rpc/SimpleScrollerRootTable/" + scrollerid;
    this.paramsScroller = {
      headers: {
        Authorization: 'Bearer ' + this.token
      },
      data: {
        Code: "1*",
        Mobile1:""
      },
    };
    console.log("Πέρασε το Token μέσα στο scrollerid -> " + this.token);

    return this.loginserviceprovider.getScrollerID(this.url, this.paramsScroller)
      .subscribe(Scroller => {
        console.log(Scroller);

      });
 }
}

#6

Looks like you’re trying to get the token from the homepage, but you should probably be getting it from the login service provider, e.g. via loginserviceprovider.getWebApi() etc.

import {LoginserviceProvider} from "../../providers/loginservice/loginservice";

export class CurrentComponent {

  token:string;

  constructor(
    private loginserviceprovider: LoginserviceProvider,
  ) { }

this.token = loginserviceprovider.SomeFunctionFromProviderThatReturnsToken()

#7

In my LoginserviceProvider i have only this code

import {HttpClient, HttpEvent, HttpHeaders} from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import {Observable} from "rxjs/Observable";

var webApihost="http://192.168.0.6:81/EBSWebApi/";
var scrollerid="ES00BACKUP/KHCApp_Items";
var scrid = "ES00BACKUP/KHCApp_Contacts";
@Injectable()
export  class LoginserviceProvider {

  url = webApihost +'api/login';

  //scroller code below//
  url2 = webApihost+"api/rpc/SimpleScrollerRootTable/" + scrollerid;

  //scrid code below
  url3 = webApihost+"api/rpc/SimpleScrollerRootTable/"+scrid;
  constructor(public http: HttpClient) {
    console.log('Hello LoginserviceProvider Provider');
    this.url=webApihost+'api/login';
    this.url2 = webApihost+"api/rpc/SimpleScrollerRootTable/" + scrollerid;
    this.url3 = webApihost+"api/rpc/SimpleScrollerRootTable/"+scrid;
  }

  getWebApi(url,params):Observable<HttpClient>{
    return this.http.post<HttpClient>
    (this.url,params);
  }
  getScrollerID(url,paramsScroller):Observable<HttpEvent<HttpClient>>{
    return this.http.get<HttpClient>
    (this.url2,paramsScroller);
  }
  getScrid(url,paramsScroller):Observable<HttpEvent<HttpClient>>{
    return this.http.get<HttpClient>
    (this.url3,paramsScroller);
  }
}

#8

If the getWebApi function returns the token (as the code above implies if I’m reading it correctly), you can use it to set a persistent variable and then create a new function that returns it as needed.

  returnedToken:string
  //...
  getWebApi(url,params):Observable<HttpClient>{
    // ...
    this.returnedToken=data.Model.WebApiToken; // or something
    // ...
  }
  getReturnedToken(){
     return this.returnedToken;
  }

Then you can use loginserviceprovider.getReturnedToken() in your other pages. You might need to make use of promises to ensure that the default null value isn’t returned.


#9

Tried it but i get this

image

Model is just a array in a Json that i get from posting my params correctly to the webservice

My edited Code below


import {HttpClient, HttpEvent, HttpHeaders} from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import {Observable} from "rxjs/Observable";

var webApihost="http://192.168.0.6:81/EBSWebApi/";
var scrollerid="ES00BACKUP/KHCApp_Items";
var scrid = "ES00BACKUP/KHCApp_Contacts";
var data;

@Injectable()
export  class LoginserviceProvider {
  token:string;
//Model:string;
  url = webApihost +'api/login';

  //scroller code below//
  url2 = webApihost+"api/rpc/SimpleScrollerRootTable/" + scrollerid;

  //scrid code below
  url3 = webApihost+"api/rpc/SimpleScrollerRootTable/"+scrid;

  constructor(public http: HttpClient) {
    console.log('Hello LoginserviceProvider Provider');
    this.url=webApihost+'api/login';
    this.url2 = webApihost+"api/rpc/SimpleScrollerRootTable/" + scrollerid;
    this.url3 = webApihost+"api/rpc/SimpleScrollerRootTable/"+scrid;
  }



  getWebApi(url, params): Observable<HttpClient>{
    this.token=data.Model.WebApiToken;
    return this.http.post<HttpClient>
    (this.url,params);
   

  }
  getToken(){
    return this.token;
  }


  getScrollerID(url,paramsScroller):Observable<HttpEvent<HttpClient>>{
    return this.http.get<HttpClient>
    (this.url2,paramsScroller);
  }
  getScrid(url,paramsScroller):Observable<HttpEvent<HttpClient>>{
    return this.http.get<HttpClient>
    (this.url3,paramsScroller);
  }
}

#10

Looks like data is undefined so it doesn’t have a Model property. This probably means the request is not returning any data, or there’s some other error in your code. You might need to sort that out first. There’s a good tutorial here: https://www.djamware.com/post/59924f9080aca768e4d2b12e/ionic-3-consuming-rest-api-using-new-angular-43-httpclient


#11

hey i think that i found an exit in my labyrinth
do you know how can i return two functions inside a function??

I want to call two functions from loginservice provider but i can’t

  ionViewWillLoad(){
    return this.loginserviceprovider.scrollerid()
  }


#12
  somefunction1(){
    return this.loginserviceprovider.scrollerid()
  }
  someFunction2(){
    // ...
  }

  ionViewWillLoad(){
    this.someFunction1(); // or just this.loginserviceprovider.scrollerid()
    this.someFunction2();
  }

You don’t need to use return for the ionViewWillLoad event; you can just include functions that you want to run before the view loads.


#13

yea! that works
actually i fixed my issue with the token
I made a timeout(5000)
and now my code runs smoothly.


#14

There is virtually always a categorically better approach than a timeout with a magic number. Refactor your provider to provide Observables of business objects and react to them. Your app will be both more reliable and more efficient.


#15

Thanks a lot for the response .

But i think is very general answer and my code (which i didnt upload) is very specific.
What do you mean by Observables of business objects?
Let me show you my code files.

src/provider/loginservice.ts

import { HttpClient,HttpEvent } from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import {Observable} from "rxjs/Observable";
import {Storage} from "@ionic/storage";

var webApihost="http://192.168.0.6:81/EBSWebApi/";
var scrollerid="ES00BACKUP/KHCApp_Items";
var scrid = "ES00BACKUP/KHCApp_Contacts";


@Injectable()
export class LoginserviceProvider {
public token:string;
  params: {
    SubscriptionPassword: string;
    model: {
      BranchID: string;
      LangID: string;
      UserID: string;
      Password: string;
    }
  };
 
  //scroller code below//
  
  paramsScroller: {
    headers: {
      Authorization: string;
    },
    data: {
      Code: string;
    }
  };

  url = webApihost + 'api/login';

  //scroller code below//
  url2 = webApihost + "api/rpc/SimpleScrollerRootTable/" + scrollerid;

  //scrid code below
  url3 = webApihost + "api/rpc/SimpleScrollerRootTable/" + scrid;

  constructor(public http: HttpClient) {
    
    console.log('Hello LoginserviceProvider Provider');
    this.url = webApihost + 'api/login';
    this.url2 = webApihost + "api/rpc/SimpleScrollerRootTable/" + scrollerid;
    this.url3 = webApihost + "api/rpc/SimpleScrollerRootTable/" + scrid;
  }


  getWebApi(url, params): Observable<HttpClient> {
    return this.http.post<HttpClient>
    (this.url, params);
  }

  getScrollerID(url, paramsScroller): Observable<HttpEvent<HttpClient>> {
    return this.http.get<HttpClient>
    (this.url2, paramsScroller);
  }

  getScrid(url, paramsScroller): Observable<HttpEvent<HttpClient>> {
    return this.http.get<HttpClient>
    (this.url3, paramsScroller);
  }

  authenticationWebApi() {

    this.url = webApihost + 'api/login';

    this.params = {
      SubscriptionPassword: 'passx',
      model: {
        BranchID: "01",
        LangID: "el-GR",
        UserID: "khcadmin",
        Password: "P@ssw0rd",
      }
    };
    //this.token = "";

    console.log("Token prin" + this.token);
    return this.getWebApi(this.url, this.params)
      .subscribe(data => {
        console.log(data);
        this.token = data.Model.WebApiToken;
       // this.storage.set('token',this.token);
        console.log("Μόλις πήρα το Token -> " + this.token);

       // this.scrollerID();
        // this.scrid();
      });

  };

  
  scrollerID() {
   // this.storage.get('token').then(value=>{this.token=JSON.parse(value)});
    console.log("ti token exw??? " + this.token);
    this.url = webApihost + "api/rpc/SimpleScrollerRootTable/" + scrollerid;
    this.paramsScroller = {
      headers: {
        Authorization: 'Bearer ' + this.token
      },
      data: {
        Code: "1*",

      },
    };
    console.log("Πέρασε το Token μέσα στο scrollerid -> " + this.token);

    return this.getScrollerID(this.url, this.paramsScroller)
      .subscribe(Scroller => {
        console.log(Scroller);

      });
  }



  scrid() {
    console.log("Mπήκα στο Scrid");

    this.url = webApihost + "api/rpc/SimpleScrollerRootTable/" + scrid;
    this.paramsScroller.data.Code = "0013168";


    //this.paramsScroller.data.Mobile1="23141231";
    return this.getScrid(this.url, this.paramsScroller)
      .subscribe(Scrid => {
        console.log(Scrid);
        console.log("βγήκα απο το Scrid")
      });
  }
}

src/pages/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {LoginserviceProvider} from "../../providers/loginservice/loginservice";
import {LoginscreenPage} from "../loginscreen/loginscreen";
import * as xml2js from 'xml2js';
import {Storage} from "@ionic/storage";

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  token;

  constructor(public navCtrl: NavController,
              private loginserviceprovider: LoginserviceProvider,
              private storage:Storage ) {
  }

  ionViewWillEnter(){

    return this.loginserviceprovider.authenticationWebApi();
  }
  
  ionViewWillLoad(){
    setTimeout(() => {
      return this.loginserviceprovider.scrollerID()
    }, 2000);
     console.log("ti exw? "+ this.token);
     
     setTimeout(()=>{
       this.navCtrl.push(LoginscreenPage);
     },1200);

  }
}

#16

By “business object” I mean things like the (currently anonymous) type of paramsScroller. HttpClient is an internal implementation detail, not something going over the wire, so I don’t see how the getXXX functions make sense. There are examples of using HttpClient here that you should be able to adapt to your situation.

A rule I always try to follow is to never mix production and consumption of Observables in the same function (or generally even in the same class). So I would get rid of all the subscriptions in your provider and instead subscribe to Observables returned by the public provider methods in your pages. That should let you get rid of all the timeouts safely and reliably.


#17

My app post and get params,requests from a Webservice.
I receive a webtoken from Webservice and in order to get more Jsons and schrollers from the webservice i use the same webtoken as a param.
Also I made a Loginscreen where EndUser has to input his credentials and store them inside storage.
Storage should make an authentication between the credentials in a JSON which exists in Webservice and the credentials that the user typed.
If they match login screen disappears.
After this whole process ,application should remember the credentials and never call the login screen again

Maybe my thought to have all my “post,request http code” inside the provider is wrong…
But i can’t find any other practical way how to get rid from subscriptions and Observables for posting and getting requests…
Every single example in the web uses this way…

The only way to get rid of all these stupid Time-outs is to seperate my subscribes from Observables?or
Not use them at all?


#18

which are the public provider methods?