Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.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 模型类注入的最佳实践(角度)_Angular - Fatal编程技术网

Angular 模型类注入的最佳实践(角度)

Angular 模型类注入的最佳实践(角度),angular,Angular,我已经阅读了关于类注入的文档,但是我不知道这些实践中哪一个更好。更具体地说:如果我有以下模型类 export class Documents{ private documentNumber:string; private countryIssuingDocument:string; private documentExpirationDate:string; private documentIssuingOffice:string; } 我想注射它 import { Compon

我已经阅读了关于类注入的文档,但是我不知道这些实践中哪一个更好。更具体地说:如果我有以下模型类

export class Documents{  
private documentNumber:string; 
private countryIssuingDocument:string;   
private documentExpirationDate:string;
private documentIssuingOffice:string;

}
我想注射它

import { Component ,Output,EventEmitter} from '@angular/core';

import {Documents} from "../../model/document.model";

@Component({
selector: 'document-screen',
templateUrl: 'document-screen.html'
})


export class DocumentScreen {

constructor(private documentData : Documents) { 
}

}
使用new关键字还是如上所述在providers数组中声明模型类更好。我认为最好在providers数组中声明我的模型类,因为这样我将拥有一个单例体系结构。我说得对吗


提前谢谢你

模型对象包含该类型的数据。您肯定不需要单个对象,您可能有许多相同类型的模型。所以使用依赖注入不是一个好主意


仅对具有逻辑且有时具有跨组件共享的数据的服务使用依赖项注入

您应该只注入“singleton”类。OP不清楚模型是如何使用的。你怎么能确定“这不是个好主意”?看起来更像是一个论点不明确的观点(这就是为什么“最佳实践”基于观点的问题被认为是离题的原因)。这很公平。对我来说,单例模型类看起来像一项服务。仅用于存储数据的服务。但从描述来看,它看起来像是一个定义用于多个位置的类。你完全有权否决我的答案:)但这不一定是一个固执己见的答案,如果问题清楚,可以通过检查答案来定量地回答。要补充这个答案。。。通常,模型类用作“类型”,而不是可注入服务。如果这个类的所有属性都是私有的。。。您使用它或将它注入其中的任何东西都不能使用这些属性。谢谢各位……这很复杂,但似乎比以前更清楚