Behaviour subject initial value null?

后端 未结 3 1760
Happy的楠姐
Happy的楠姐 2020-12-03 04:15
private customer: Subject = new BehaviorSubject(null);

setCustomer(id, accountClassCode) {
    this.customer.next({\'id\': id, \'account         


        
      
      
      
3条回答
  •  悲哀的现实
    2020-12-03 04:56

    Try structuring this way your service:

    Service:

    @Injectable()
    export class MyService {
        customerUpdate$: Observable;
    
        private customerUpdateSubject = new Subject();
    
        constructor() {
            this.customerUpdate$ = this.customerUpdateSubject.asObservable();
        }
    
        updatedCustomer(dataAsParams) {
            this.customerUpdateSubject.next(dataAsParams);
        }
    }
    

    Remember to add MyService to providers.

    Where you update your client (if this is the case), you do something like this:

    Component (The one that triggers):

    constructor(private myService: MyService) {
            // I'll put this here, it could go anywhere in the component actually
            // We make things happen, Client has been updated
            // We store client's data in an object
            this.updatedClient = this.myObjectWithUpdatedClientData;  // Obj or whatever you want to pass as a parameter
            this.myService.updatedCustomer(this.updatedClient);
        }
    

    Component (The one that is Subscribed):

    this.myService.customerUpdate$.subscribe((updatedClientData) => {
                // Wow! I received the updated client's data
                // Do stuff with this data!
            }
        );
    

    From what I understood, you are trying to pass data from 1 component to another. You get your Client's data and send it over your App to another component, right? That's why I posted this solution.

    If you are interested in other types of subscriptions, read this:

    Angular 2 special Observables (Subject / Behaviour subject / ReplaySubject)

提交回复
热议问题