无法在2个组件之间实时同步数据

时间:2018-12-21 09:55:29

标签: angular

我有2个不同的角度组件,一个用于向非实时数据库的数据库中添加数据,另一个用于检索这些数据,问题是当我想在调用saveData()时在第一个组件中添加数据时),然后将其添加到我在同一服务中调用getData()时所拥有的数据数组,然后从getData组件中调用if,然后自动显示它而无需刷新,这是我的代码:

store.service.ts:

storeChanged = new Subject<Store[]>()
    baseUrl = 'MyURL';
    store: Store[];
    constructor(private http: HttpClient) {}
    getData() {
        return this.http.get<Store[]>(`${this.baseUrl}/store.php`, {
            observe: 'body',
            responseType: 'json'
        }).subscribe((response) => { 
            this.store= response['data'];
    })}
  saveData(store) {
         return this.http.post(`${this.baseUrl}/createStore.php`, store)
            .subscribe((store) => {
                    this.store.push(store['data']);
  })}

store.component.ts

subscription: Subscription;
  store: Store[];
  constructor(private storeService: storeService) { }
  ngOnInit() {
    this.storeService.getData();
  }

任何帮助将不胜感激!

已编辑

addFeatures.component.ts

 store: Store;
  id: number;
  constructor(private storeService: storeServiceService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.route.params.subscribe(
      (params: Params) =>
      {
        this.id = +params['id'];
        this.getStoreById(this.id);
      }
    );
  }

  getStoreById = (id) => {
    this.storeService.getStoreById(id).subscribe(response => this.store = 
    response);
  }

然后使用* ngFor

将我的商店映射到模板中

1 个答案:

答案 0 :(得分:0)

您可以通过执行以下操作将store: Store[]更改为可观察值:

store: Observable<Store[]> = this.storeChanged.asObservable();

getData()方法中:

...
.subscribe((response) => { 
    this.storeChanged.next(response['data']);
 })}

saveData()方法中:

...
 .subscribe((store) => {
     this.storeChanged.next([...this.storeChanged.getValue(),store['data']]);
  })}

并在 store.component.ts

ngOnInit() {
    this.storeService.store.subscribe(response => this.store = response);
    this.storeService.getData();
  }

希望有帮助

更新

要使用getValue(),您需要将storeChanged更改为BehaviorSubject并为其传递初始值。

storeChanged: BehaviorSubject<Store[]> = new BehaviorSubject([]);

更新2

如果您要使用返回Observable的方法来检索单个项目

getStoreByID = (id): Observable<Store> => {
    return this.storeChaged.pipe(map( storeArr => storeArr.find(item => item.id === id)))
}

在组件中:

getStoreByID = (id) => {
    this.storeService.getStoreByID(id).subscribe(response => this.store = response)
}