简体   繁体   English

如何在Angular 7中将服务函数作为可观察值返回?

[英]How to return a service function as an observable in Angular 7?

I have this service.ts code: 我有这个service.ts代码:

export class BasicOperationService {

  constructor() { }

  delete(service: any, object: any, data: any): Observable<any> {
    const id = this.getId(object);
    let index: number;

    for (let i = 0; i < data.length; i++) {
      if ( data[i].id === id) {
        index = i;
        break;
      }
    }

    return service.delete(id).subscribe(result => {
        data.splice(index, 1);
        return data;
      }, error => {
        console.log(error);
        return data;
      });
  }
}

And I have this component.ts: 我有这个component.ts:

delete(object: any, id: number) {
  this.loadingId = id;

  this.basicOperation.delete(this.photoalbumService, object, this.content.data)
    .subscribe(result => {
      this.content.data = result;
      this.loadingId = 0;
    });
}

And now I get this error message: 现在,我收到此错误消息:

TypeError: this.basicOperation.delete(...).subscribe is not a function

How can I return from BasicOperationService's delete() method as an observable? 如何从BasicOperationService的delete()方法返回可观察到的结果?

Maybe I'm misunderstanding, but you perhaps you should 也许我误会了,但也许你应该

return service.delete(id);

and not subscribe. 而不订阅。

Then, subscribe only in the the component that consumes the service. 然后,仅订阅使用该服务的组件。

you can serve data as observable using Rxjs "of", eg 您可以使用“ of”的Rxjs提供可观察的数据,例如

return of({id:1,data:"hello word})

But, in your case, you must use switchMap, because you must wait to service.delete finish. 但是,在这种情况下,必须使用switchMap,因为必须等待service.delete完成。

delete(service: any, object: any, data: any): Observable<any> {
    const id = this.getId(object);
    let index: number;

    for (let i = 0; i < data.length; i++) {
      if ( data[i].id === id) {
        index = i;
        break;
      }
    }

    return service.delete(id).pipe(
       //we don't return the result of delete, else "data.splice"
       switchMap(result =>{
           data.splice(index,1);
           return of(data);
       }))
  }

Then you subscribe in the component 然后您订阅该组件

Update as IngoBürk say in his comments, in this case NOT use switchMap, just you can use map. 就像IngoBürk在评论中所说的那样进行更新 ,在这种情况下,请不要使用switchMap,而可以使用map。

delete(service: any, object: any, data: any): Observable<any> {
    ...
    return service.delete(id).pipe(
       map((result)=>{
           data.splice(index,1);
           return data;
       }))
  }

"map" transform the result and the "return" must be an object. “地图”转换结果,“返回”必须是一个对象。 "switchMap" is util if you want to return a different observable -this is because in swithmap you must return an observable- 如果您要返回其他可观察的值,则“ switchMap”为util,这是因为在swithmap中,您必须返回一个可观察的值-

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

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