从订阅访问属性

时间:2016-10-14 08:01:48

标签: angular rxjs

我在如何在角度2项目中访问rxJS订阅的属性时遇到问题。

我知道我的服务正在运行,因为我可以将{{selectedCustomer.name}}放在我的模板中,它显示了我的名字,我只是无法弄清楚如何在我的组件中访问它,所以我可以将其分配为ngInit。

如果有人可以协助如何做到这一点,将不胜感激

服务

import { Injectable } from '@angular/core';

import { Customer } from "./customer-model";

import { AngularFire, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';

import "rxjs/add/operator/filter";

declare var firebase: any;

@Injectable()
export class CustomerService {

    // customer: Customer;
    customer: FirebaseObjectObservable<Customer[]>;
    customers: FirebaseListObservable<Customer[]>;

    constructor(private af: AngularFire) { }

    getCustomers(category: string = null) {
        if (category != null) {
            this.customers = this.af.database.list('customer', {
                query: {
                    orderByChild: 'category',
                    equalTo: category
                }
            });

        } else {

            this.customers = this.af.database.list('customer') as FirebaseListObservable<Customer[]>;

        }

        return this.customers;
    }

    getCustomer(customerIndex: number) {

        this.af.database.object('/customer/' + customerIndex)
            .subscribe(customer => {
                this.customer = customer;
            });
        return this.customer;
    }

    addCustomer(customer: Customer) {

        // Get new unique key for customer
        var customerKey = firebase.database().ref().child('customer').push().key;

        // Create reference to new customer key
        var newCustomer = {};
        newCustomer['/customer/' + customerKey] = customer;

        return firebase.database().ref().update(newCustomer);
    }

    deleteCustomer(customerIndex: number) {
         this.af.database.object('/customer/' + customerIndex).remove();
    }

}

模板

    <form [formGroup]="myForm" (ngSubmit)="onAddCustomer()">
  <md-card class="demo-card demo-basic">
    <md-toolbar color="primary">Edit</md-toolbar>
    <md-card-content>
      <br>
      <table style="width: 100%" cellspacing="0">
        <tr>
          <td>
            <md-input placeholder="Organisation" style="width: 100%" formControlName="name" type="test" id="name" #name></md-input>
          </td>
          <td>
            <md-input placeholder="Description" style="width: 100%" formControlName="description" type="test" id="description" #description></md-input>
          </td>
          <td>
            <md-input placeholder="Image Url" style="width: 100%" formControlName="imagePath" type="test" id="imagePath" #imagePath></md-input>
          </td>
        </tr>

      </table>
    </md-card-content>
  </md-card>

</form>

组件

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms";

import { Subscription } from 'rxjs/Rx';

import { FirebaseObjectObservable } from 'angularfire2';

import { Customer } from '../customer-model';
import { CustomerService } from '../customer.service';

@Component({
  selector: 'mj-customer-edit',
  templateUrl: './customer-edit.component.html',
  styleUrls: ['./customer-edit.component.css']
})
export class CustomerEditComponent implements OnInit, OnDestroy {

  myForm: FormGroup;
  error = false;
  errorMessage = '';

  private subscription: Subscription;
  private customerIndex: number;
  selectedCustomer: FirebaseObjectObservable<Customer[]>;

  constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private customerService: CustomerService,
    private router: Router) { }

  ngOnInit() {

    this.subscription = this.route.params.subscribe((params: any) => {
      this.customerIndex = params['key'];
      this.selectedCustomer = this.customerService.getCustomer(this.customerIndex);
    })
    **This is where I want to assign the values on my form to the customer object that i get back from the service**

    this.myForm = this.fb.group({
      name: ['', Validators.required],
      description: ['', Validators.required],
      imagePath: ['', Validators.required],
    });
  }

  ngOnDestroy(){
    this.subscription.unsubscribe();
  }

}

1 个答案:

答案 0 :(得分:1)

您也需要订阅您的客户服务。

this.subscription = this.route.params.subscribe((params: any) => {
          this.customerIndex = params['key'];
          this.customerService.getCustomer(this.customerIndex).subscribe((res) => {
              this.selectedCustomer = res;
              //extra assignments with selectedCustomer object here.
          });
        })

编辑:添加了服务代码

getCustomer(customerIndex: number) {

    return this.af.database.object('/customer/' + customerIndex);
}