【问题标题】:Http request doesnot take the inputvalue again for the second timeHttp请求第二次没有再次取输入值
【发布时间】:2018-01-14 09:26:54
【问题描述】:

我有一个我用 html 编写的输入框,我通过.ts 文件中的两种数据绑定获取我在输入框中输入的任何内容。InputBox 在父组件中

<input [(ngModel)]="inputValue" placeholder="Search FAQ" type="text"/>
<button type="submit" (click)="onRecievingResults()"></button>

这是.ts 文件,在这里我获取输入文本并使用参数字段将值传递给子组件。

onRecievingResults() {
    this.router.navigate(['results', this.inputValue], {relativeTo: this.route});
}

在这里,我使用 subscribe 获取输入值,并通过 http 请求服务,我第一次得到结果。但是当我再次传递该值时,它不会获取该值并给出结果。

ngOnInit() {
this.route.params
.subscribe(
(params: Params) => {
this.inputValue = params['inputValue'];
}
);

this.faqService.getServers(this.inputValue)
    .subscribe(
    (data) => {
        this.item = data.items;
        console.log(this.item);
        },
        (error) => console.log(error)
    );
}

HTTP 请求服务

getServers(inputValue) {
    console.log(inputValue);
    return this.http.get(Staticdata.apiBaseUrl + "/2.2/search/advanced?key="+ Staticdata.key +"&access_token="+ Staticdata.access_token +"&/2.2/search/advanced?order=desc&sort=activity&accepted=True&closed=True&title=" + inputValue + Staticdata.redirectUrl + "&filter="+ Staticdata.filters)
        .map(
        (response: Response) => {
            const items = response.json();
            return items;
        },
    )
    .catch(
        (error: Response) => {
            return Observable.throw(error);
        }
  );
}

【问题讨论】:

    标签: angular angular2-routing angular2-template angular2-forms angular2-services


    【解决方案1】:

    根据您的逻辑,这是正确的行为,让我们跟随事件的流程。

  • 起初组件结果不存在
  • 在第一次单击时,您将路由到结果组件
  • 角度实例化结果组件并执行 ngOnInit 方法 第一次执行你的逻辑
  • 您第二次单击该按钮。
  • angular 不会重新实例化结果组件,因为它已经存在,不会调用 getServers(this.inputValue)。

    但是 params 订阅中的逻辑是因为 params 值被改变而被执行的,所以你可以通过在 params 订阅回调中移动 getServers(this.inputValue) 来解决它。如下:
    ngOnInit() {
        this.route.params.subscribe(  (params: Params) => {
           this.inputValue = params['inputValue'];
    
           this.faqService.getServers(this.inputValue).subscribe( 
             (data) => {
               this.item = data.items;
               console.log(this.item);
             },
             (error) => console.log(error)
           );
        });
    }
    
  • 【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-05
      • 2019-11-13
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      相关资源
      最近更新 更多