我是新來的角,我無法將數據從數據服務綁定到FormGroup。我能夠訪問視圖中的屬性就好了,但是相同的屬性在控制器內部未定義,我嘗試創建表單組並將其設置爲初始表單控件值。無法訪問控制器內部的角2屬性
型號
export class Dog {
constructor(
id: number,
name: string,
age: number
) { }
}
服務
getDog(): Promise<Dog> {
return this.http.get(this.baseUrl + '/api/endpoint').toPromise().then(res.json());
}
組件 我然後從我的組件一樣調用這個服務:
export class DogComponent implements OnInit {
form: FormGroup;
dog: Dog;
constructor(private service: DogService, private fb: FormBuilder) { }
ngOnInit(): void {
this.getData();
this.createForm();
}
getData() {
this.service.getDog().then(res => this.dog = res);
}
createForm() {
this.form = this.fb.group({
id: [this.dog.id],
name: [this.dog.name],
age: [this.dog.age]
});
}
}
查看
<form [formGroup]="form">
<input formControlName="name" />
<input formControlName="age" />
</form>
我能像設置[值] =「名稱」輸入值,但我希望能夠設置那些在方法的CreateForm。任何想法爲什麼屬性可用於視圖但不在控制器內
的[我如何返回從一個異步調用的響應?]可能的複製(https://開頭stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Igor
另外你的服務不應該編譯,看看'then'語句。 – Igor