javascript - Angular 2 中推荐的服务架构

标签 javascript typescript angular

目前,我将所有服务都放在一个服务目录中,并且多个组件依赖于它们,并且一个服务依赖于另一服务等等。服务和组件的依赖关系图看起来很疯狂。因此,在某些情况下,当尝试将一项服务注入(inject)另一项服务时,我会收到 DI 错误。以下是我的一种情况的示例:

import {stuff} from 'stuffs';

@Injectable()
export class ApiService
{   
    getData(): Observable<string>{
        return this.http.get(url).map(v => v.json());
    }
}

@Injectable()
export class SomeService
{   
    constructor(private apiService: ApiService){

    }
}

@Component()
export class SomeComponent
{
    constructor(private apiService: ApiService,
        private someService: SomeService){

    }
}

我没有找到任何组织服务的推荐模式,因此在编写了大量代码后,我请求一些指导,可以为我指明正确的方向并重构它。

最佳答案

Angular 2 网站上有一个样式指南:https://angular.io/docs/ts/latest/guide/style-guide.html#!#application-structure

Do be descriptive with file names and keep the contents of the file to exactly one component.

Avoid files with multiple components, multiple services, or a mixture.

Why? We spend less time hunting and pecking for code, and become more efficient. If this means we want longer file names, then so be it.

而且在小纸条上还写着:

There are deviations of the 1 per file rule when we have a set of very small features that are all related to each other, as they are still easily identifiable.

还有一个总体文件夹和文件结构指南以及更多内容,您可能会在其中找到有趣的内容。

并查看依赖于其他服务的服务的答案:https://stackoverflow.com/a/33979228/5706293

关于javascript - Angular 2 中推荐的服务架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37867264/

相关文章:

javascript - 我如何遍历 react.js 中的对象数组并在对象中添加价格值,如下所示

javascript - 使用动态 Tab 时 Summernote 不工作

javascript - Ng Bootstrap 轮播全屏

javascript - Angular 2 选择菜单值

javascript - 从 Electron Container IPC Channel 接收数据时,变更检测会间歇性工作

javascript - 使用 highcharts 从 mysql 数据库向折线图添加动态数据

javascript - 使用sqlite3在node.js中变量的有效性

TypeScript:深偏?

typescript - 接受特定类型对象的 keyof 吗?

reactjs - Typescript 高阶组件作为装饰器