【问题标题】:Chained http get calls, Angular 2, typescript链式 http get 调用,Angular 2,打字稿
【发布时间】:2017-11-28 15:12:18
【问题描述】:

在 Angular 2 表单中,我需要从 http get call 检索名字和姓氏,提供一个 user_id,它由之前的 http get call 检索到另一个端点。

我知道async http get calls 也有类似的问题,但这些都没有真正帮助我。

所以,第一个调用接收到user_id 字段,而不向服务器提供任何内容:

/API/system/session/unusedid

它返回这个 -->

{user_name":"rgar003","session_id":"0635400936","is_technical_user":"false","user_id":"403"

有了这个user_id (403),我可以调用另一个端点并检索它的userNamelastName

/API/identity/user/403    //403 or whatever the user_id is

它返回这个 -->

{"job_title":"dsf","userName":"rgar003","lastname":"Garcia","firstname":"Robert"}

所以,我需要在禁用的表单输入中提供名字 + 姓氏。现在我只是提供user_id

应显示姓名和姓氏的禁用字段的模板:

<div class="col-sm-5">
    <label for="petitioner">Petitioner</label>
    <input [(ngModel)]="data.petitioner" type="text" class="form-control" name="petitioner" disabled>
</div>

home 组件,从中调用一个函数从后端加载请愿者user_id

constructor(private workflowService: WorkflowService, private parametersService: UrlParametersService, private _ref: ChangeDetectorRef) {

this.formMode = parametersService.formMode;

  // origin:  /API/system/session/unusedId
  this.workflowService.loadPetitioner().subscribe(
    res => {
      this.data.petitioner= res;
    }
  );

包含该函数的workflow.service

constructor(private http: Http, private parametersService: UrlParametersService, private router: Router, private _configurations: ConfigurationsService) {}

public loadPetitioner(): Observable<string> {
  return this.http.get("/API/system/session/unusedId", {withCredentials: true}).map(value => value.json().user_name);
}

我尝试了不同的链接方式,但都失败了。 如果我打电话给/API/identity/user/403,所以提供user_id 硬编码,那么获取名字+姓氏就可以了。像这样:

getPetitionerFirstNamePlusLastName(): Observable<string>{
return this.http.get("/API/identity/user/403",  {withCredentials: true}).map(value =>(value.json().firstname + " " +  value.json().lastname));
}

我似乎这里有一个异步问题,但我无法解决它,即使在检查了其他类似问题之后也是如此。

【问题讨论】:

    标签: angular typescript asynchronous http-get chaining


    【解决方案1】:

    试试这个

    this.workflowService.loadPetitioner().concatMap( res => {
          let id = res;
          return this.getPetitionerFirstNamePlusLastName(id);
    }).subscribe( res => {
          // Do stuff with the user
    });
    

    在 getPetitionerFirstNamePlusLastName 中添加 id 作为参数

    getPetitionerFirstNamePlusLastName(id:number): Observable<string>{
         return this.http.get("/API/identity/user/" + id,  {withCredentials: true}).map(value =>(value.json().firstname + " " +  value.json().lastname));
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-07
      • 2016-04-03
      • 2017-04-24
      • 1970-01-01
      • 2016-04-07
      • 2017-11-21
      • 1970-01-01
      • 2016-10-07
      • 2022-11-17
      相关资源
      最近更新 更多