Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 编写Object.Object.Method的最佳实践_Angular_Typescript - Fatal编程技术网

Angular 编写Object.Object.Method的最佳实践

Angular 编写Object.Object.Method的最佳实践,angular,typescript,Angular,Typescript,我需要像这样调用object.object.method 是的,我可以,但我不知道这样做是不是一个好办法 API文件 export class ApiService { public customer = new Customer(); } class Customer { public foo() { return "Bar"; } } 当我想使用客户的方法时,我这样写 另一个文件 const api = new ApiService();

我需要像这样调用object.object.method

是的,我可以,但我不知道这样做是不是一个好办法

API文件

export class ApiService {
     public customer = new Customer();
}

class Customer {
     public foo() {
          return "Bar";
     }
}
当我想使用客户的方法时,我这样写

另一个文件

const api = new ApiService();
api.customer.Foo();
请告诉我这件事

我的英语不是很好,我不知道关键字搜索这个

谢谢大家


编辑:将Foo改为Foo(谢谢:Nurbol Alpysbayev)

一切都很好。除非你不应该写大写的方法。因此,将
Foo
更改为just
Foo
,您的一切都很好。

您这样做非常好。虽然我想说,由于您访问属性“customer”只是为了调用一个方法,您可以通过将该属性设置为私有并为此属性创建一个getter来减少对该属性的访问。例如:

export class ApiService {
     private _customer = new Customer();

     get customer(): Customer {
         return this._customer;
     }
}

class Customer {
     public foo() {
          return "Bar";
     }
}
这是一个很好的实践,通过这种方式,ApiService类中的客户实例是只读的,防止其他代码意外修改此实例

您仍然可以这样做:

const api = new ApiService();
api.customer.foo();

最后,正如前面发表的评论所指出的,保持一致,用小写字母开始你的方法,后面的单词用大写字母开始

代码看起来不错。有什么问题吗?@MattMcCutchen只是问这样做的最佳实践。我想问的一个问题是,为什么要这样做?您的用例是什么?我想按用例(如客户、员工等)划分API类,并调用1个文件(API服务)