【问题标题】:call a service from a service and return its result从服务调用服务并返回其结果
【发布时间】:2020-08-09 22:39:44
【问题描述】:

我编写了一个服务来收集一些数据并组装一个对象。该服务然后调用另一个服务(使用 HTTPClient 调用 API)并返回它刚刚创建的资源的 ID。这基本上可以工作并且看起来很“正常”:

(省略了几行)

@Injectable({
  providedIn: 'root'
})
export class CourseWizardService {
  // Page Data
  (...)

  constructor(
    private courseService: CourseService) { }

在该服务的一个函数中,我调用另一个函数并接收结果:

// assemble step data to final object then call creation API & return new Id (to navigate)
  finish() {
    const newCourse = CourseFactory.empty();

    // set values
    (...)


    // ToDO: notify caller about new ID
    this.courseService.addCourse(newCourse).subscribe(courseId => {
      ??RETURN?? = courseId;
      this.reset();
    });

  }

我的目标是将“courseId”从 finish() 函数返回给“外部”调用者(一个组件),这样我就可以使用路由器导航到该新资源。但是当我将函数更改为 finish(): number 并返回该 ID 时,我遇到了一些“同步问题”。

我不是 observables 的专家,是不是我必须创建一个新的 observable - 可能使用 of() - 并将原始 observable “提交”给调用者?

这是我想要在组件中做的事情:

// finish: save item
this.courseWizardService.finish();

// receive/pass-through the ID so I can navigate
this.router.navigate(['/home']);

更新 我不知道如何将“courseId”(API 的结果)从调用服务传递给组件。

(CourseWizardService)

finish() {
    // (...)
    return this.courseService.addCourse(newCourse).pipe(
      tap(courseId => { // how to pass that over?
        this.reset();
    }));
}


(Component)

onSubmit() {
    this.courseWizardService.finish().pipe(
      take(1)
      ).subscribe(() => this.router.navigate(['courses', courseId])); // where would "courseId" come from?
}

【问题讨论】:

  • 什么“同步问题”?

标签: angular service observable


【解决方案1】:

您可以使用 observable 来返回完成调用。

finish() {
    ...
    return this.courseService.addCourse(newCourse).pipe(
      tap(courseId => {
        ??RETURN?? = courseId;
        this.reset();
    }));
}

在您的现役服务中:

this.courseWizardService.finish().pipe(take(1)).subscribe(() =>
  this.router.navigate(['/home']);
, err => {
  // ...some error debug here
});

【讨论】:

  • 能否再给我一些指导?我很挣扎,我不知道如何返回 courseId 以在调用方开始导航。我正在更新问题,因为我似乎无法在此处格式化。
  • n/m - 弄清楚了,这很容易 :-) 谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
  • 2016-07-30
  • 2013-07-16
相关资源
最近更新 更多