简体   繁体   中英

Subjects in Angular

So imagine you have an angular app with the below component and service files. In a component the users subscribe to this subject in the service file.

Now imagine that someone makes the server request in the service file and gets the response from the server.

When we receive the server response and trigger the Subject with the next() method, will only we receive the data in the component that is subscribed to this Subject or basically every person who is currently using this app and has this subscription open in his component?

Component

export class exampleComponent implements OnInit {
  ngOnInit() {
    this.exampleService.exampleSubject().subscribe();
  }
}

Service

export class exampleService {
  exampleSubject = new Subject();

  someOtherMethodWithHttpRequest() {
    return this.http.get(url).pipe(map(data => this.exampleSubject.next()));
  }
}

It will because it is a Subject, and subjects are multicast.

edited: my initial answer was no, because only BehaviorSubject and ReplaySubject are multicast . This is wrong , all Subjects are multicast.

Using a BehaviorSubject in this case is a good idea though: it guarantees that every subscriber will receive the value from the api call, even if they subscribe after the api call occurred. If you subscribe to a Subject after it has emitted its value, you will never receive the value from that api call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM