【发布时间】:2020-08-07 03:33:06
【问题描述】:
我对 Angular 很陌生,并且在将数组传递给 不同路径 上的不同(与父/子相关)组件时遇到了麻烦。我想要在我的应用程序中单击一个按钮以将预订标记为“已接受”,并在不同的视图中显示相同的已接受预订数组(更改路线)。
我尝试实现一个 BehaviorSubject,但它不起作用。我可以成功设置数组,但是当我想通过在第二个组件中订阅它来检索它时,它只显示主题的初始值,在本例中为“Hello World”。请帮助我,我已经尝试了一周,观看 youtube 视频和谷歌搜索,但我找不到什么问题。 PD:如果有人想知道的话,我没有在 app.component.ts 中添加 sharedService 作为提供程序。
First component
import { Component, OnInit } from '@angular/core';
import {SharedService} from '../../services/shared.service';
import {share} from 'rxjs/operators';
@Component({
selector: 'app-turnos',
templateUrl: './turnos.component.html',
styleUrls: ['./turnos.component.css'],
providers:[TurnoService]
})
export class TurnosComponent implements OnInit {
public turnos: Turno;
public status;
constructor(
private _sharedService: SharedService
) { }
acceptBooking(booking){
this._sharedService.addToAccepted(booking);
this._sharedService.acceptedBookingsSubject.pipe(share()).subscribe(res=>console.log(res));
//this is just to watch the response, which shows the correct array, but it works only in this component
}
}
现在,共享服务
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {Turno} from '../models/turno';
import {Observable} from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class SharedService{
private acceptedBookings=[];
public acceptedBookingsSubject= new BehaviorSubject<any[]>(['Hello World']);
constructor(){
}
addToAccepted(turno : Turno){
this.acceptedBookings.push(turno);
this.acceptedBookingsSubject.next(this.acceptedBookings);
}
}
最后是第二个组件,它必须显示所有已接受的预订。我已经使用了使用异步管道的管道(share())和订阅()选项来查看是否有任何工作,但是当我调用 console.log 时,两者都只显示“Hello World”。
import { Component, OnInit} from '@angular/core';
import {SharedService} from '../../services/shared.service';
import {Observable} from 'rxjs';
import {Turno} from '../../models/turno';
import {share} from 'rxjs/operators';
@Component({
selector: 'app-turnoaceptado',
templateUrl: './turnoaceptado.component.html',
styleUrls: ['./turnoaceptado.component.css'],
providers:[SharedService]
})
export class TurnoaceptadoComponent implements OnInit {
public acceptedBookings;
public array:Observable<any[]>;
public test;
ngOnInit(): void {
this.array = this._sharedService.acceptedBookingsSubject.asObservable();
this.array.subscribe(response=>this.acceptedBookings=response);
this.test=this.array.pipe(share());
console.log(this.test);
console.log(this.acceptedBookings);
}
constructor(private _sharedService: SharedService) { }
}
【问题讨论】:
-
我有一个问题需要更好地理解才能更好地回答:您什么时候第一次在第二个组件中调用订阅?通常,根据我的经验,您应该在更新之前订阅。
-
@LuDeveloper 我已经尝试在 OnInit 和构造函数中订阅,我对此不太了解,因为我是 Angular 新手。在更新其他组件之前如何订阅?
标签: angular rxjs observable subscription behaviorsubject