Angular 2 - 访问订阅值

时间:2017-08-18 21:30:17

标签: angular observable

如何正确访问formBuilder中的this.existingUsers?现在console.log(value)没有显示在控制台中。 console.log(this.id)会返回正确的参数。

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],
        })
      };

}

2 个答案:

答案 0 :(得分:0)

我并不完全清楚你要做什么......但你可能需要.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文件夹中)

答案 1 :(得分:-2)

您尝试在设置之前获取asynchronous数据。

当某些内容异步时,它将在未来运行,订阅是异步的。

订阅功能中的所有内容都在ngOnInit完成后运行。这意味着,您目前正在尝试在first_name设置之前访问existing_user

尝试将this.userForm内容移动到订阅功能中,如下所示:

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],
      })
    });