2016-10-14 2 views
1

У меня возникают проблемы с обработкой доступа к свойствам подписки rxJS в проекте с угловым 2.Доступ к свойствам из подписки

Я знаю, что моя служба работает, поскольку я могу разместить {{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

Вам также необходимо подписаться на обслуживание клиентов.

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. 
      }); 
     }) 

Edit: Добавлен код службы

getCustomer(customerIndex: number) { 

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

Спасибо - если я стараюсь, что я получаю ошибку компиляции говоря Type 'Клиент []' не может быть назначен для типа 'FirebaseObjectObservable '. – ccocker

+0

Можете ли вы обновить свой вопрос и добавить код услуги? – Sefa

+0

Да, жаль, что помогло бы. Я обновил вопрос с помощью служебного кода. – ccocker

Смежные вопросы