简体   繁体   English

订阅来自不同组件的服务响应

[英]Subscribe to service response from a different component

I have a upload component that uploads file(s) to a server using upload.service.ts's upload method in angular.我有一个上传组件,它使用 angular 中的 upload.service.ts 上传方法将文件上传到服务器。 The server returns a JSON response in that method.服务器在该方法中返回 JSON 响应。 I also have another component which is interested in the JSON response.我还有另一个对 JSON 响应感兴趣的组件。 But how can the another component subscribe to the JSON response.但是另一个组件如何订阅 JSON 响应。

If this service is a singleton, then you could set up an observable that holds the reponse objects.如果此服务是 singleton,那么您可以设置一个包含响应对象的 observable。

upload.service.ts上传.service.ts

@Injectable({ providedIn: 'root' })
export class UploadService {
  private uploadResponseSource = new Subject<any>();
  public uploadResponse$ = this.uploadResponseSource.asObservable();

  upload() {
    return this.http.post(...).pipe(
      tap(response => this.uploadResponseSource.next(response))
    );
  }
}

You could then subscribe to this observable from a component to receive the object response.然后,您可以从组件订阅此 observable 以接收 object 响应。

Some component一些组件

export class SomeComponent implements OnInit {
  uploadResponse: any;

  ngOnInit() {
    this.uploadService.uploadResponse$.subscribe(
      response => { this.uploadResponse = response }
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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