HTTP请求第二次不重新取输入值

Http request doesnot take the inputvalue again for the second time

我有一个输入框,我已经写在 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});
}

这里我使用订阅获取输入值,我通过 http 请求服务,我首先得到结果 time.But 当我再次传递该值时,它不接受该值并给出结果。

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);
        }
  );
}

按照你的逻辑,这是正确的行为,让我们顺着事件的流程来。

  • 起初组件结果不存在
  • 在第一次点击时,您正在路由到结果组件
  • angluar 实例化结果组件并执行 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)
           );
        });
    }