我並不完全清楚你正在嘗試做什麼......但你可能需要.map方法中的代碼。就像這樣:
export class UserComponent implements OnInit {
existingUser: any = {};
ngOnInit() {
this.activatedRoute.params.subscribe((params: Params) => {
this.id = params['id'];
console.log(this.id);
this.db.object(`/users/${this.id}`).map(value => {
console.log(value);
this.existingUser = value;
console.log(this.existingUser);
this.userForm = this.formBuilder.group({
first_name: [this.existingUser.first_name, Validators.required],
})
})
});
};
}
或者把這些代碼在一個被從這裏調用的方法。
更新:這是我的應用程序,做類似的例子:
ngOnInit(): void {
this.productForm = this.fb.group({
productName: ['', [Validators.required,
Validators.minLength(3),
Validators.maxLength(50)]],
productCode: ['', Validators.required],
starRating: ['', NumberValidators.range(1, 5)],
tags: this.fb.array([]),
description: ''
});
// Read the product Id from the route parameter
this.route.params.subscribe(
params => {
let id = +params['id'];
this.getProduct(id);
}
);
}
getProduct(id: number): void {
this.productService.getProduct(id)
.subscribe(
(product: IProduct) => this.onProductRetrieved(product),
(error: any) => this.errorMessage = <any>error
);
}
onProductRetrieved(product: IProduct): void {
if (this.productForm) {
this.productForm.reset();
}
this.product = product;
if (this.product.id === 0) {
this.pageTitle = 'Add Product';
} else {
this.pageTitle = `Edit Product: ${this.product.productName}`;
}
// Update the data on the form
this.productForm.patchValue({
productName: this.product.productName,
productCode: this.product.productCode,
starRating: this.product.starRating,
description: this.product.description
});
this.productForm.setControl('tags', this.fb.array(this.product.tags || []));
}
您可以找到全套的代碼在這裏:https://github.com/DeborahK/Angular2-ReactiveForms(在APM文件夾)
你不顯示什麼'this.db.object'可能是,但你永遠不'subscribe'什麼返回。另外你似乎認爲'existingUser'會以某種方式在後續行中可用 - 如果是這種情況,*你不需要可觀察的*。 – jonrsharpe
[如何從異步回調函數返回值?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) –