Arul Vivek
Arul Vivek

Reputation: 39

Access the common method from other component

Here I am using some method for frequently used methods in common method ts file. If I am going to access these method I got null values Please help me out.

CommonMethod.ts:

    GetCategoryList(){
        let Mylist = [];
        this.auth.Get("Master/Category").then((user) => {
          Mylist= user.json();
        });
        return Mylist;
      }

My Another component:

I am trying to access common method ts file here. by below way.

    import {CommonMethod} from './CommonMethod';
    ...
    ...
    construtor(private com:CommonMethod){}
    ngOninit(){
         console.log(this.com.GetCategoryList());
    }

Upvotes: 1

Views: 30

Answers (2)

Scott.N
Scott.N

Reputation: 172

Should update your common method:

GetCategoryList(): Promise<any>{
        let Mylist = [];
        return this.auth.Get("Master/Category").then((user) => {
          Mylist= user.json();
          Promise.resolve(Mylist);
        });

      }

And

ngOninit(){
        this.com.GetCategoryList().then(results=>{
            console.log(results);
        });

   }

Upvotes: 0

SiddAjmera
SiddAjmera

Reputation: 39432

this.auth.Get is going to be async in nature due to which the return MyList line will get called even before the callback to the then method is called and the data is arrived and set in MyList.

You can use the async await syntax to fix it:

async GetCategoryList() {
  let Mylist = [];
  const user = await this.auth.Get("Master/Category");
  Mylist = user.json();
  return Mylist;
}

You can then use it like this in your Component:

import {CommonMethod} from './CommonMethod';

...
...

construtor(private com: CommonMethod) {}

async ngOninit() {
  const myList = await this.com.GetCategoryList();
  console.log(myList);
}

PS: Make sure that CommonMethod is a service and is added to the providers array of your @NgModule

Upvotes: 1

Related Questions