I have been learning Angular 4 for a couple of weeks now. I cannot seem to figure out how to pass data from one component to another as my components were simple before. I figured out that the best for me to use is Behaviorsubject, because I have a form component that fills out from a list component when I edit a customer instead of making a new one.
CustomerList
import { Component, OnInit } from '@angular/core';
import { DataService } from '../services/data.service';
import {Subscription} from 'rxjs/Subscription';
@Component({
selector: 'app-cust-list',
templateUrl: './cust-list.component.html',
styleUrls: ['./cust-list.component.css']
})
export class CustListComponent implements OnInit {
isEdit:boolean = false;
subscription:Subscription;
customers: any[];
customer = {
id: '',
name: '',
email: '',
phone: ''
}
constructor(public dataservice:DataService) {
console.log('werkz');
this.dataservice.get().subscribe (customers =>{
this.customers = customers;
});
if(this.isEdit){
this.subscription = this.dataservice.setCust.subscribe(customer =>
this.customer = customer)
}
}
CustomerForm
import { Component, OnInit } from '@angular/core';
import { DataService } from '../services/data.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-cust-form',
templateUrl: './cust-form.component.html',
styleUrls: ['./cust-form.component.css']
})
export class CustFormComponent implements OnInit {
subscription:Subscription;
constructor(public dataservice: DataService){
this.subscription = this.dataservice.getCust(cust);
}}
Data.service
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
@Injectable()
export class DataService{
public custSent = new BehaviorSubject<object>([]);
set setCust(customer){
this.custSent.next(customer);
}
get getCust(){
return this.custSent.getValue();
}
}
Is this the correct way to do it? If so can someone lead me to what is wrong? If it is not I might need a push in the right direction. Thank you in advance.
Aucun commentaire:
Enregistrer un commentaire