Send data from service to observable Get request

后端 未结 2 376
自闭症患者
自闭症患者 2021-01-27 21:42

I am new to Angular and Observables. I have a service that receives a URL I want to pass to my observable and render data every time a new URL is passed to it with NgFor. Any ex

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-27 22:21

    I think I understand your problem.

    The http.get(url) is a single-use observable. It's not a stream that can be triggered multiple times like subjects can. You will need to create your own subject and use that as a proxy.

    export class ClientService {
    
     constructor(private http: HttpClient) {
     }
    
     private eventPublisher: Subject = new Subject();
    
     receiveEvent(eventId){
       // call http client here, and publish results to event publisher
       const eventUrl = eventId;
       this.http.get(eventUrl).subscribe(response => {
         this.eventPublisher.next(response);
       });
     }
    
     renderEvent(eventUrl): Observable{
      // do not subscribe to http client here, subscribe to event publisher
      return this.eventPublisher.asObservable();
     }
    

    This is the pub-sub design pattern (publisher - subscriber). It might be useful to read up on other solutions to this design pattern using Angular, as this is a fairly trivial example.

    Edit:

    You will also want to unsubscribe in your component once you're done with the subscription to avoid memory leaks.

    Something like this is a simple pattern:

    export class MyComponent implements OnInit, OnDestroy() {
      constructor(private myService: MyService) { }
    
      private destroyed: Subject = new Subject();
    
      ngOnInit(): void {
        this.myService.myMethod().pipe(
          takeUntil(() => this.destroyed)
        ).subscribe(() => { 
          // do stuff
        });
      }
    
      ngOnDestroy(): void {
        this.destroyed.next(undefined);
        this.destroyed.complete();
      }
    }
    

    Although it does get repetitive if you need to start doing it a lot. I personally use this method: https://stackoverflow.com/a/45709120/5367916

提交回复
热议问题