我有一个共享服务和两个兄弟组件 当我在这两个组件之间共享对象并且我尝试更改其中一个对象的属性时它会更新但是当我有String类型共享数据它没有更新。如果这是工作为什么我需要RXJS那么
我知道它是对象所以通过引用它应该得到更新但它不会写在Angular文档的任何地方
这是我的服务和组件代码
服务
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class AppServiceService {
data = [{ name: 'init' }];
sharedData: Data[];
// sharedData = new BehaviorSubject<Data[]>(this.data);
constructor() {
this.sharedData = this.data;
}
getData() {
return this.sharedData;
}
}
export interface Data {
name: string;
city?: string;
}
COMPONENT 1
import { Component, OnInit } from '@angular/core';
import { AppServiceService, Data } from '../app-service.service';
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {
data: Data[];
constructor(private appService: AppServiceService) { }
ngOnInit() {
this.data = this.appService.getData();
}
changeValue() {
this.data[0].name = 'kashif';
this.data[0].city = 'mumbra';
}
}
COMPONENT 2
import { Component, OnInit } from '@angular/core';
import { AppServiceService, Data } from '../app-service.service';
@Component({
selector: 'app-villain',
templateUrl: './villain.component.html',
styleUrls: ['./villain.component.css']
})
export class VillainComponent implements OnInit {
data: Data[];
constructor(private appService: AppServiceService) { }
ngOnInit() {
this.data = this.appService.getData();
}
}