2017-10-05 116 views
-1

我一直在學習Angular 4幾個星期了。我似乎無法弄清楚如何將數據從一個組件傳遞到另一個組件,因爲我的組件之前很簡單。我發現我最好使用的是Behaviorsubject,因爲當我編輯客戶而不是創建新的表單組件時,我有一個表單組件填充表單組件。組件之間的數據傳遞Angular4

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

難道這就是科爾等方式來做到這一點?如果有的話,有人能帶領我發生什麼事?如果不是,我可能需要朝正確的方向推動。先謝謝你。

+0

您已經測試了嗎?它工作嗎?如果沒有,你可以給[mcve]說明它的具體問題嗎? – jonrsharpe

+0

這個答案我給了https://stackoverflow.com/questions/46560989/angular-2-4-communication-between-two-component-via-a-shared-service/46561386#46561386如果沒有測試,那麼不要發佈您的問題 –

回答

0

更改服務功能的名稱如下(刪除getset):

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>([]); 

setCust(customer){ 
     this.custSent.next(customer); 
} 

getCust(){ 
    return this.custSent.getValue(); 
} 
}