从其他组件访问通用方法

时间:2018-12-04 09:32:50

标签: html angular angular5

在这里,我将某些方法用于常用方法ts文件中的常用方法。如果我要访问这些方法,则会得到空值,请帮帮我。

CommonMethod.ts:

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

我的另一个组件:

我试图在此处访问通用方法ts文件。通过下面的方式。

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

2 个答案:

答案 0 :(得分:1)

this.auth.Get本质上将是async,由于return MyList行将在调用then方法的回调和数据被调用之前被调用。到达并设置在MyList中。

您可以使用async await语法对其进行修复:

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

然后可以在组件中像这样使用它:

import {CommonMethod} from './CommonMethod';

...
...

construtor(private com: CommonMethod) {}

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

PS::确保CommonMethod是一项服务,并已添加到providers的{​​{1}}数组中

答案 1 :(得分:0)

应该更新您的常用方法:

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

      }

还有

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

   }