Angular 2: Functions to be used across all compone

2020-05-16 04:50发布

I have an angular 2 webpack project where I currently have some functions that are repeated throughout several components. I would like to inherit all of these components from a "master" class OR component (whichever works), in order to be able to call my functions from all my components that need them.

As an example, if I have a function foo in 3 different components:

foo(s: string){
  console.log(s);
}

I would like you move this function to another file/class/components:

class parent{
  foo(s: string){
    console.log(s);
  }
}

And having someway to call my foo function from my a given component. For instance:

class child{
  constructor(){
    foo("Hello");
  }
}

How would I do this using Angular 2 / Typescript?

4条回答
贪生不怕死
2楼-- · 2020-05-16 05:04

You can create utils.ts which contains all common funcitons

export default class Utils {
    static doSomething(val: string) { return val; }
    static doSomethingElse(val: string) { return val; }
}

Then you can use as below

import Utils from './utils'

export class MyClass {
     constructor()
     {
         Utils.doSomething("test");
     }
}
查看更多
看我几分像从前
3楼-- · 2020-05-16 05:19

If you want to use inheritance it's the extends keyword:

parent.class.ts

class parent{
  foo(s: string){
    console.log(s);
  }
}

child.component.ts

import { Component } from "@angular/core";
import { parent } from "./parent.class";

@Component({
  selector: 'child',
  template: `<div>{{myMessage}}</div>`
})
export class child extends parent {
  myMessage: string = "Hello";

  constructor(){
    super.foo(this.myMessage);
  }
}

http://plnkr.co/edit/iQfqphLCx62Qy5lYVJa5?p=preview

Note that any decorate information is lost, so don't apply it to the base class and expect that the children will have it.

That's pretty much it for using inheritance for these purposes. The other methods of a shared service or even a static class are also viable. It really depends on what you're trying to accomplish with them and what pattern best matches your use case.

查看更多
倾城 Initia
4楼-- · 2020-05-16 05:20

You can create class which all methods are static

export class Utils {
    public static log(msg:string){
        console.log(msg);
    }
}

then, just import it where you want to use

import {Utils} from './utils'

class parent{
   foo(s: string){
     Utils.log(s);
   }
}

class child{
   constructor(){
      Utils.log("Hello");
   }
}
查看更多
在下西门庆
5楼-- · 2020-05-16 05:28

I would use a service, here's a shortened example from one of my apps:

import {Injectable} from '@angular/core';
import * as _ from 'lodash';

@Injectable()

export class UtilsService {

  findObjectIndex(list: any[], obj: any, key: string): number {

    return _.findIndex(list, function(item) {
      return obj[key] === item[key];
    });
  }

  findObjectByQuery(list: any[], key: string, query: string): any {

    return _.find(list, function(item) {
      return item[key].toLowerCase() === query.toLowerCase();
    });
  }
}

Then you can inject this service into anything, which is really useful and you keep things DRY.

You would simply inject it like so:

import {UtilsService} from 'app/shared';

export MyComponent {

  constructor(private utils: UtilsService) {
    utils.findObjectIndex([], {}, 'id'); // just an example usage
  }
}

EDIT:

As @aalielfeky's answer says you could use static functions.

However, I would personally avoid static functions because they are borderline impossible to test properly as well as giving you hell once the time comes where you need to inject something in the constructor that is going to be used in one of the functions. Since static functions can't use anything that's injected.

Don't make the same mistake as me because you will end up having to rewrite a lot of code.

查看更多
登录 后发表回答