我已经学习了Angular 4几周了。我似乎无法弄清楚如何将数据从一个组件传递到另一个组件,因为我的组件之前很简单。我发现我最好使用的是Behaviorsubject,因为我有一个表单组件,当我编辑客户而不是创建一个新客户时,它会从列表组件中填充。
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 :(得分:0)
更改服务功能名称,如下所示(删除get
和set
):
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();
}
}