im developing an admin panel where the admin can see all the bookings that have been requested and select those who he will accept; and I want to display those 'accepted' bookings in a different tab (...

问题描述 投票:0回答:1
At ngOnInit, just add:

Then you can choose if you prefer to create a subscription on it or use pipe async.

shared Service

import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {Turno} from '../models/turno';


@Injectable({
  providedIn: 'root',
})

export class SharedService{

    private acceptedBookings=[];

    public acceptedBookingsSubject= new BehaviorSubject<Turno[]>([]);
    //public turno:Turno;

    constructor(){ 
    }

addToAccepted(turno : Turno){

    this.acceptedBookings.push(turno);
    this.acceptedBookingsSubject.next(this.acceptedBookings);   
        console.log(this.acceptedBookingsSubject);
}



}

Additional tip, once you set the SharedService with

Second component, which consumes the service and has to display the array.

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:Observable<Turno[]>;

          ngOnInit(): void {
  }

  constructor(private _sharedService: SharedService) {

            this._sharedService.acceptedBookingsSubject.pipe(share());

             }



}

, you don't need to put the SharedService on any providers array.

I have created a demo:
arrays angular rxjs behaviorsubject subject
1个回答
0
投票

我正在开发一个管理面板,在那里管理员可以看到所有的预订要求,并选择那些谁,他将接受;我想显示这些 "接受 "预订在不同的标签(不同的组件,在一个不同的路线)。我使用了一个带有BehaviorSubject的SharedService,但它没有工作。我在第二个组件中得到的只是一个匿名Subject数组,是空的。我没有显示第一个组件,它将预订发送到服务,因为它工作正常。请帮助我

this.acceptedBookings = this._sharedService.acceptedBookingsSubject.asObservable();

这里是第二个组件。

在第二个组件的html中,我使用了async管道

© www.soinside.com 2019 - 2024. All rights reserved.