-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();
}
}
これはCORRですそれをやる方法?もしそうなら、誰かが私を間違っているものに導くことができますか?もしそうでなければ、私は正しい方向へのプッシュが必要かもしれません。前もって感謝します。
は、あなたがそれをテストしたことがありますか?それは動作しますか?もしそうでなければ、特定の問題を説明する[mcve]を与えることができますか? – jonrsharpe
この回答は、https://stackoverflow.com/questions/46560989/angular-2-4-communication-between-two-component-via-a-shared-service/46561386#46561386に記載されています。 –