TypeScript를 사용하여 Angular 2 구성 요소에서 모델 클래스를 선언하려면 어떻게 해야 합니까?
저는 Angular 2와 TypeScript가 처음이고 모범 사례를 따르려고 노력하고 있습니다.
간단한 JavaScript 모델({ })을 사용하는 대신 TypeScript 클래스를 만들려고 합니다.
하지만 Angular 2는 그것을 좋아하지 않는 것 같습니다.
내 코드는:
import { Component, Input } from "@angular/core";
@Component({
selector: "testWidget",
template: "<div>This is a test and {{model.param1}} is my param.</div>"
})
export class testWidget {
constructor(private model: Model) {}
}
class Model {
param1: string;
}
그리고 나는 그것을 다음과 같이 사용합니다.
import { testWidget} from "lib/testWidget";
@Component({
selector: "myComponent",
template: "<testWidget></testWidget>",
directives: [testWidget]
})
Angular:에서 오류가 발생합니다.
예외: testWidget에 대한 일부 매개 변수를 확인할 수 없습니다.
그래서 저는 모델이 아직 정의되지 않았다고 생각했습니다.위로 올려드릴게요.
지금은 예외입니다.
원본 예외: 모델에 대한 공급자 없음!
어떻게 해야 하나요?
편집: 답변해주신 모든 분들께 감사드립니다.그것은 저를 올바른 길로 이끌었습니다.
이것을 생성자에게 주입하려면 구성 요소의 공급자에 추가해야 합니다.
이것은 작동하는 것으로 보입니다.
import { Component, Input } from "@angular/core";
class Model {
param1: string;
}
@Component({
selector: "testWidget",
template: "<div>This is a test and {{model.param1}} is my param.</div>",
providers: [Model]
})
export class testWidget {
constructor(private model: Model) {}
}
저는 이것을 시도합니다.
을 모을별파분할다니합일라는 .model.ts
:
export class Model {
param1: string;
}
구성 요소로 가져옵니다.이를 통해 다른 구성요소에서 사용할 수 있다는 추가적인 이점을 얻을 수 있습니다.
Import { Model } from './model';
구성 요소에서 초기화:
export class testWidget {
public model: Model;
constructor(){
this.model = new Model();
this.model.param1 = "your string value here";
}
}
html에서 적절하게 액세스합니다.
@Component({
selector: "testWidget",
template: "<div>This is a test and {{model.param1}} is my param.</div>"
})
최신 툴과 기술에 적응하는 것이 중요하기 때문에 @PatMigliaccio의 의견을 답변에 추가하고 싶습니다.
사중인경우를 .
angular-cli
전화하셔도 됩니다ng g class model
그러면 모델이 원하는 이름으로 대체됩니다.
문제는 당신이 추가하지 않았다는 것입니다.Model
둘 중 어느 쪽으로bootstrap
될이다) (그싱글될것다이이또톤는은것),▁the다또는▁(),▁(▁to그), 것▁or싱which것.providers
구성 요소 정의 배열:
@Component({
selector: "testWidget",
template: "<div>This is a test and {{param1}} is my param.</div>",
providers : [
Model
]
})
export class testWidget {
constructor(private model: Model) {}
}
은 리고예정, 당은야합니다해를 정의해야 .Model
다보위에의 Component
하지만 그의 파일에 넣는 것이 더 나을 것입니다.
그러나 여러 인스턴스를 만들 수 있는 클래스로 사용하려면 다음을 사용하는 것이 좋습니다.new
.
@Component({
selector: "testWidget",
template: "<div>This is a test and {{param1}} is my param.</div>"
})
export class testWidget {
private model: Model = new Model();
constructor() {}
}
export class Car {
id: number;
make: string;
model: string;
color: string;
year: Date;
constructor(car) {
{
this.id = car.id;
this.make = car.make || '';
this.model = car.model || '';
this.color = car.color || '';
this.year = new Date(car.year).getYear();
}
}
}
||는 존재하지 않는 기본 데이터에 대해 매우 복잡한 데이터 개체에 매우 유용할 수 있습니다.
. .
component.ts 또는 service.ts 파일에서 응답 데이터를 모델로 역직렬화할 수 있습니다.
// Import the car model
import { Car } from './car.model.ts';
// If single object
car = new Car(someObject);
// If array of cars
cars = someDataToDeserialize.map(c => new Car(c));
같은페에모있구클뒤래소모선스있합어언사다으니용야해로므되델이에성요이델지지이를 사용해야 합니다.forwardRef
고로참을 Class
개체를 항상 별도의 파일에 보관하여 이 작업을 수행하지 마십시오.
export class testWidget {
constructor(@Inject(forwardRef(() => Model)) private service: Model) {}
}
또한 올바른 개체를 참조하기 위해 보간 보기를 변경해야 합니다.
{{model?.param1}}
당신이 해야 할 더 좋은 것은, 당신이 당신의 것을 가질 수 있다는 것입니다.Model
클래스는 다른 파일로 정의한 다음 필요할 때 로 가져옵니다.또한 가지고 있습니다.export
클래스 이름 앞에 입력하여 가져올 수 있습니다.
import { Model } from './model';
내 코드는
import { Component } from '@angular/core';
class model {
username : string;
password : string;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
username : string;
password : string;
usermodel = new model();
login(){
if(this.usermodel.username == "admin"){
alert("hi");
}else{
alert("bye");
this.usermodel.username = "";
}
}
}
그리고 html은 다음과 같습니다.
<div class="login">
Usernmae : <input type="text" [(ngModel)]="usermodel.username"/>
Password : <input type="text" [(ngModel)]="usermodel.password"/>
<input type="button" value="Click Me" (click)="login()" />
</div>
@brendon의 답변에 있는 코멘트가 암시하는 대로 각도-cli를 사용할 수 있습니다.
다음을 시도해 볼 수도 있습니다.
ng g class modelsDirectoy/modelName --type=model
/* will create
src/app/modelsDirectoy
├── modelName.model.ts
├── ...
...
*/
명심할 사항: ng g class
!== ng g c
그러나 사용할 수 있습니다.ng g cl
각-cli 버전에 따라 바로 가기로 설정합니다.
이 질문이 다소 오래된 질문이라는 것은 알고 있지만, 모델 변수를 테스트 위젯 클래스에 잘못 추가했다는 점을 지적하고 싶습니다.모형 변수가 필요한 경우 구성 요소 생성자를 통해 모형 변수를 전달하려고 하면 안 됩니다.서비스 또는 다른 유형의 주입기만 그런 식으로 전달할 수 있습니다.다른 구성 요소 내부에서 테스트 위젯을 인스턴스화하고 모델 개체를 전달해야 하는 경우 각진 코어 OnInit 및 Input/Output 디자인 패턴을 사용하는 것이 좋습니다.
예를 들어 코드는 다음과 같습니다.
import { Component, Input, OnInit } from "@angular/core";
import { YourModelLoadingService } from "../yourModuleRootFolderPath/index"
class Model {
param1: string;
}
@Component({
selector: "testWidget",
template: "<div>This is a test and {{model.param1}} is my param.</div>",
providers: [ YourModelLoadingService ]
})
export class testWidget implements OnInit {
@Input() model: Model; //Use this if you want the parent component instantiating this
//one to be able to directly set the model's value
private _model: Model; //Use this if you only want the model to be private within
//the component along with a service to load the model's value
constructor(
private _yourModelLoadingService: YourModelLoadingService //This service should
//usually be provided at the module level, not the component level
) {}
ngOnInit() {
this.load();
}
private load() {
//add some code to make your component read only,
//possibly add a busy spinner on top of your view
//This is to avoid bugs as well as communicate to the user what's
//actually going on
//If using the Input model so the parent scope can set the contents of model,
//add code an event call back for when model gets set via the parent
//On event: now that loading is done, disable read only mode and your spinner
//if you added one
//If using the service to set the contents of model, add code that calls your
//service's functions that return the value of model
//After setting the value of model, disable read only mode and your spinner
//if you added one. Depending on if you leverage Observables, or other methods
//this may also be done in a callback
}
}
기본적으로 구조/모델에 불과한 클래스는 주입하면 안 됩니다. 이는 제공된 범위 내에서 해당 클래스의 공유 인스턴스를 하나만 가질 수 있음을 의미하기 때문입니다.이 경우 testWidget이 인스턴스화될 때마다 종속성 인젝터에 의해 단일 모델 인스턴스가 생성됩니다.모듈 수준에서 제공되는 경우 해당 모듈 내의 모든 구성 요소 및 서비스 간에 공유되는 인스턴스는 하나뿐입니다.
대신 표준 개체 지향 방식을 따르고 클래스의 일부로 전용 모델 변수를 생성해야 하며 인스턴스를 인스턴스화할 때 해당 모델에 정보를 전달해야 하는 경우 상위 모듈에서 제공하는 서비스(주입식)에서 처리해야 합니다.이것이 의존성 주입과 통신이 각도로 수행되는 방법입니다.
또한 다른 일부가 언급했듯이 모델 클래스를 별도의 파일로 선언하고 클래스를 가져와야 합니다.
각 문서 참조로 돌아가서 다양한 주석 및 클래스 유형에 대한 기본 페이지를 검토할 것을 강력히 권장합니다. https://angular.io/guide/architecture
모듈, 구성 요소 및 서비스/의존성 주입 섹션은 아키텍처 수준에서 각도를 사용하는 방법을 이해하는 데 필수적인 섹션이므로 특히 주의를 기울여야 합니다.Angular는 매우 높은 수준이기 때문에 매우 건축적으로 무거운 언어입니다.브라우저 비교를 위한 우려 분리, 의존성 주입 팩토리 및 자바스크립트 버전 관리가 주로 당신을 위해 처리되지만, 당신은 그들의 애플리케이션 아키텍처를 올바르게 사용해야 하며 그렇지 않으면 당신이 예상한 대로 작동하지 않는다는 것을 알게 될 것입니다.
아래와 같이 구성 요소 디렉토리에 model.ts를 만듭니다.
export module DataModel {
export interface DataObjectName {
propertyName: type;
}
export interface DataObjectAnother {
propertyName: type;
}
}
그런 다음 위의 구성 요소 가져오기에서 '/.model'에서 {DataModel}을(를) 가져옵니다.
export class YourComponent {
public DataObject: DataModel.DataObjectName;
}
DataObjectName의 모든 속성을 가지고 있어야 합니다.
언급URL : https://stackoverflow.com/questions/38398877/how-do-i-declare-a-model-class-in-my-angular-2-component-using-typescript
'programing' 카테고리의 다른 글
Ubuntu에서 apt-get 업데이트를 실행할 때 Docker Repository에 릴리스 파일이 없음 (0) | 2023.08.20 |
---|---|
어떻게 하면 트위터 부트스트랩 하위 메뉴를 왼쪽에서 열 수 있습니까? (0) | 2023.08.20 |
ngSubmit은 페이지를 Angular 2 형식으로 새로 고칩니다. (0) | 2023.08.15 |
테이블을 가로질러 결합할 때 객체의 인덱스/분해를 최적화하는 방법은 무엇입니까? (0) | 2023.08.15 |
Python CSV 오류: 줄에 NULL 바이트가 포함되어 있습니다. (0) | 2023.08.15 |