Angular2 - 多个依赖的顺序http api调用

时间:2016-08-20 12:08:40

标签: api http service angular observable

我正在构建一个Angular2应用程序,其中一个组件需要进行多个API调用,这些调用依赖于之前的API调用。

我目前有一项服务,它会进行API调用以获取电视节目列表。对于每个节目,我需要多次调用不同的API来逐步完成结构,以确定节目是否存在于Plex服务器上。

API文档为here

对于每个节目,我需要进行以下调用并获取正确的数据以确定它是否存在:(假设我们有变量<TVShow>, <Season>, <Episode>

http://baseURL/library/sections/?X-Plex-Token=xyz会告诉我: title="TV Shows" key="2"

http://baseURL/library/sections/2/all?X-Plex-Token=xyz&title=<TVShow>会告诉我:key="/library/metadata/2622/children"

http://baseURL/library/metadata/2622/children?X-Plex-Token=xyz会告诉我:index="<Season>" key="/library/metadata/14365/children"

http://baseURL/library/metadata/14365/children?X-Plex-Token=xyz会告诉我:index="<Episode>"这意味着我的剧集已存在。

响应是在json中,我删除了很多多余的文本。在每个阶段,我都需要检查是否存在正确的字段(<TVShow>, <Season>, <Episode>),以便它们可以用于下一次调用。如果没有,我需要返回该节目不存在。如果是的话,我可能想要为节目返回一个id。

我看过很多例子,包括promise,async&amp; flatmap,但我不知道如何根据我见过的其他例子来解决这个问题。

以下是我获取节目列表的内容。 (shows.service.ts)

export class ShowsHttpService {
    getShows(): Observable<Show[]> {
        let shows$ = this._http
            .get(this._showHistoryUrl)
            .map(mapShows)
            .catch(this.handleError);
        return shows$;
    }
}

function mapShows(response:Response): Show[] {
    return response.json().data.map(toShow);
}

function toShow(r:any): Show {
    let show = <Show>({
        episode: r.episode,
        show_name: r.show_name,
        season: r.season,
        available : false,    // I need to fill in this variable if the show is available when querying the Plex API mentioned above.
    });
    // My best guess is here would be the right spot to call the Plex API as we are dealing with a single show at a time at this point, but I cannot see how.
    return show;
}

以下是组件(shows.component.ts)

中的相关代码
public getShows():any {
    this._ShowsHttpService
        .getShows()
        .subscribe(w => this.shows = w);
    console.log(this.shows);
}

奖励积分

以下是明显的下一个有趣但不必要的问题:

  1. 第一个API查询将比等待所有其他查询快得多(4个查询* ~10个节目)。可以返回初始列表,然后在准备就绪时使用available状态进行更新。
  2. 获取key="2"的第一个Plex调用只需要执行一次。它可能是硬编码的,但相反,它可以被执行一次并记住吗?
  3. 有没有办法减少API调用的数量?我可以看到我可以删除显示过滤器,并在客户端上搜索结果,但这也不理想。
  4. 每个节目的4个调用必须按顺序进行,但每个节目可以并行查询以获得速度。这可以实现吗?
  5. 任何想法都会非常感激!

1 个答案:

答案 0 :(得分:3)

不确定我是否完全理解你的问题,但这就是我所做的:

我进行第一次http调用,然后当subscribe触发时,它调用completeLogin。然后,我可以使用自己的完整函数触发另一个http调用并重复链接。

这是组件代码。用户已填写登录信息并按下登录信息:

onSubmit() {
   console.log(' in on submit');
   this.localUser.email = this.loginForm.controls["email"].value;
   this.localUser.password = this.loginForm.controls["password"].value;
   this.loginMessage = "";
   this.checkUserValidation();
}

checkUserValidation() { 
   this.loginService.getLoggedIn()
      .subscribe(loggedIn => {
         console.log("in logged in user validation")
         if(loggedIn.error != null || loggedIn.error != undefined || loggedIn.error != "") {
            this.loginMessage = loggedIn.error;
         }
      });

      this.loginService.validateUser(this.localUser);
}

这将调用loginservice ValidateUser方法

validateUser(localUser: LocalUser) {
   this.errorMessage = "";
   this.email.email = localUser.email;
   var parm = "validate~~~" + localUser.email + "/"
   var creds = JSON.stringify(this.email);
   var headers = new Headers();
   headers.append("content-type", this.constants.jsonContentType);

   console.log("making call to validate");
   this.http.post(this.constants.taskLocalUrl + parm, { headers: headers })
      .map((response: Response) => {
         console.log("json = " + response.json());
         var res = response.json();
         var result = <AdminResponseObject>response.json();
         console.log(" result: " + result);
         return result;
      })
      .subscribe(
         aro => {
            this.aro = aro
         },
         error => {
            console.log("in error");
            var errorObject = JSON.parse(error._body);
            this.errorMessage = errorObject.error_description;
            console.log(this.errorMessage);
         },
         () => this.completeValidateUser(localUser));
            console.log("done with post");
     }

completeValidateUser(localUser: LocalUser) {
   if (this.aro != undefined) {
      if (this.aro.errorMessage != null && this.aro.errorMessage != "") {
         console.log("aro err " + this.aro.errorMessage);
         this.setLoggedIn({ email: localUser.email, password: localUser.password, error: this.aro.errorMessage });
      } else {
         console.log("log in user");
         this.loginUser(localUser);
      }
   } else {
      this.router.navigate(['/verify']);
   }

}

在我的登录服务中,我调用授权服务,该服务返回一个可观察的令牌。

loginUser(localUser: LocalUser) {
   this.auth.loginUser(localUser)
   .subscribe(
      token => {
         console.log('token = ' + token)
         this.token = token
      },
      error => {
         var errorObject = JSON.parse(error._body);
         this.errorMessage = errorObject.error_description;
         console.log(this.errorMessage);
         this.setLoggedIn({ email: "", password: "", error: this.errorMessage });
      },
      () => this.completeLogin(localUser));
}

在授权服务中:

loginUser(localUser: LocalUser): Observable<Token> {
   var email = localUser.email;
   var password = localUser.password;

    var headers = new Headers();
    headers.append("content-type", this.constants.formEncodedContentType);

    var creds:string = this.constants.grantString + email + this.constants.passwordString + password;
    return this.http.post(this.constants.tokenLocalUrl, creds, { headers: headers })
         .map(res => res.json())
}

此代码中的重点是,首先调用登录服务的validateUser方法,在响应时,根据返回信息,如果有效,我在登录服务上调用loginUser方法。只要你需要,这条链就可以继续。您可以设置类级变量来保存链中每个方法所需的信息,以便决定下一步该做什么。

另请注意,您可以订阅服务中的退货并在那里处理它,它不必返回到组件。

好的,接下来:

public getShows():any {
   this._ShowsHttpService
      .getShows()
      .subscribe(
         w => this.shows = w,
         error => this.errorMessage = error,
         () => this.completeGetShows());
}

completeGetShow() {

   //any logic here to deal with previous get;

   this.http.get#2()
      .subscribe(
         w => this.??? = w),
         error => this.error = error,
         () => this.completeGet#2);
}

completeGet#2() {

   //any logic here to deal with previous get;

   this.http.get#3()
      .subscribe(
         w => this.??? = w),
         error => this.error = error,
         () => this.completeGet#3);
}

completeGet#3() {

   //any logic here to deal with previous get;

   //another http: call like above to infinity....
}