【问题标题】:Inject an Angular service into an exported function将 Angular 服务注入到导出的函数中
【发布时间】:2019-07-23 19:19:48
【问题描述】:

我有一个可注入的服务来显示 toast 消息。我想在另一个我只有一些导出函数的打字稿文件中使用它。

这是我的服务

import { Injectable } from "@angular/core"; 
import { NotifierService } from "angular-notifier";

@Injectable({
  providedIn: "root"
})
export class Notifier {
  notifier: NotifierService;

  constructor(private notifierService: NotifierService) {
    this.notifier = this.notifierService;
  }

  notifiy(type, message) {
    this.notifierService.notify(type, message);
  }
}

这是导出的函数,我需要根据条件在其中显示一些祝酒词。这包含在另一个打字稿文件中。

export function validateFile(file) {
let type = getFileType(file.name);
let size = file.size;
switch (type) {
    case "image": {
      if (size > 10000000) {
        return false;
      } else {
        return true;
      }
    }

case "audio": {
  if (size > 200000000) {
    return false;
  } else {
    return true;
  }
}

case "video": {
  if (size > 300000000) {
    return false;
  } else {
    return true;
  }
}

case "compress": {
  if (size > 200000000) {
    return false;
  } else {
    return true;
  }
}

default: {
  return false;
}
  }
}

如何在这个函数中使用通知服务的通知方法??

【问题讨论】:

  • 看看我在this 线程上的旧答案。另外,如果您想要替代解决方案,我建议您考虑接受的答案。
  • 你为什么需要那个,我的意思是服务是为托管这种逻辑而创建的,我的意思是你为什么不创建另一个服务来处理通知逻辑并直截了当访问 DI 和所有注册服务(包括通知服务)?
  • 它工作。但它现在给出循环依赖警告。所以我想这不是最好的解决方案。
  • 您可以创建另一个模块(例如 InjectorModule)并在该模块中创建注入器实例。然后在您的应用模块中导入新创建的模块。这样你就可以打破循环依赖。

标签: angular typescript dependency-injection


【解决方案1】:
    import { Injectable } from "@angular/core"; 

    @Injectable({
      providedIn: "root"
    })
    export class NotifierService {
    notifySubject$ = new Subject<{}>();

     notify(type, message) {
        this.notifySubject.next({type, message}));
      }

    subscribeToNotifications() {
    return this.notifySubject.asObservable();
}
    }

====================

   export class SomeClass {

   constructor(private notifier: NotifierService) {}

export function validateFile(file) {
let type = getFileType(file.name);
let size = file.size;
switch (type) {
    case "image": {
      this.notifier.notify(type, 'some message')
      if (size > 10000000) {
        return false;
      } else {
        return true;
      }
    }

case "audio": {
      this.notifier.notify(type, 'some message')
  if (size > 200000000) {
    return false;
  } else {
    return true;
  }
}

case "video": {
      this.notifier.notify(type, 'some message')
  if (size > 300000000) {
    return false;
  } else {
    return true;
  }
}

case "compress": {
      this.notifier.notify(type, 'some message')
  if (size > 200000000) {
    return false;
  } else {
    return true;
  }
}

default: {
  return false;
}
  }
}

}

【讨论】:

    猜你喜欢
    • 2014-05-18
    • 1970-01-01
    • 2016-07-15
    • 2017-08-24
    • 2021-06-25
    • 2018-11-16
    • 2016-12-09
    • 1970-01-01
    相关资源
    最近更新 更多