我目前有一个服务,它进行API调用以获取电视节目列表.对于每个节目,我需要多次调用不同的API来逐步完成结构,以确定节目是否存在于Plex服务器上.
API文档是here
对于每个节目,我需要进行以下调用并获取正确的数据以确定它是否存在:(假设我们有变量< TVShow>,< Season>,< Episode>)
http:// baseURL / library / sections /?X-Plex-Token = xyz会告诉我:
title =“电视节目”key =“2”
HTTP://基本URL /库/分段/ 2 /所有的X-Plex的令牌= XYZ&安培;标题= LT; TVShow>?会告诉我:key =“/ library / Metadata / 2622 / children”
http:// baseURL / library / Metadata / 2622 / children?X-Plex-Token = xyz告诉我:index =“< Season>”键= “/库/元/ 14365 /儿童”
http:// baseURL / library / Metadata / 14365 / children?X-Plex-Token = xyz告诉我:index =“< Episode>”这意味着我存在的情节.
响应是在json中,我删除了很多多余的文本.在每个阶段,我需要检查是否存在正确的字段(< TVShow>,< Episode>),以便它们可用于下一次调用.如果没有,我需要返回该节目不存在.如果是的话,我可能想要为节目返回一个id.
我看了很多例子,包括promise,async& flatmap,但我不知道如何根据我见过的其他例子来解决这个问题.
> How to chain Http calls in Angular2
> Angular 2.0 And Http
> Angular 2 – What to do when an Http request depends on result of another Http request
> Angular 2 chained Http Get Requests with Iterable Array
> nodejs async: multiple dependant HTTP API calls
> How to gather the result of Web APIs on nodeJS with ‘request’ and ‘async’
这是我获取节目列表的内容. (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); }
奖励积分
以下是明显的下一个有趣但不必要的问题:
>第一个API查询比等待所有其他查询要快得多(4个查询* ~10个节目).可以返回初始列表,然后在准备好时使用可用状态进行更新.
>获取密钥=“2”的第一个Plex调用只需要执行一次.它可能是硬编码的,但相反,它可以执行一次并记住吗?
>有没有办法减少API调用的数量?我可以看到我可以删除显示过滤器,并在客户端上搜索结果,但这也不是理想的.
>每个节目的4个调用必须按顺序进行,但每个节目可以并行查询以提高速度.这可以实现吗?
任何想法将不胜感激!
我进行第一次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),() => this.completeGet#3); } completeGet#3() { //any logic here to deal with prevIoUs get; //another http: call like above to infinity.... }