2017-06-13 140 views
1

我目前在角2工作。在这里我正面临一个有趣的问题。我在我的标题中有一个搜索栏,它将我重定向到“resultsComponent”。在resultsComponent它显示我的搜索结果。但是当我站在resultsComponent并且想要搜索别的东西。当我在搜索栏中输入要搜索的内容时,它不会重定向我,因为我已经在该组件中。由于其中resultsComponent的构造函数不会再次命中。我无法获得查询值,因为我正在构造函数中获取查询值。我如何重新加载这个构造函数。这里是我的代码示例。 HeaderSearch如何在角度2中刷新或重新加载组件?

<input type="search" name=query [(ngModel)]="query" #quer="ngModel" class="form-control" class="form-control" required> 
           <button type="submit"(click)="Search()" class="btn"> 
            <i class="icon icon-header-search"></i> 
           </button> 

.TS

Search(){ 
// alert(this.query) 
//console.log(this.query); 
     localStorage.setItem('val',JSON.stringify(this.query)); 
this.router.navigate(['/result']); 

     } 

result.ts

constructor() { 
    this.query=JSON.parse(localStorage.getItem('val')); 
    } 

this.httpService.searchGeneric(this.query,1).subscribe(
     data => { 
     this.Getspecs = data; 
    this.count=data['totalItems']; 
     } 
    ); 

,当我站在结果组件。任何人都可以告诉我的搜索如何继续工作,并在我再次搜索时更新结果组件。任何帮助或建议是高度赞赏。

回答

0

我可以帮助你的出发点。 在页眉搜索组件中为结果组件定义viewchild。 在结果组件中定义了一个方法,它将完成构造函数中所做的所有工作,只需在构造函数中保留依赖关系injectiom即可。

现在敲击搜索按钮时,搜索方法将在头部搜索组件中调用,在此方法中使用viewChild对象调用结果组件方法,所有内容都将被刷新。下面是一些示例代码:

搜索组件:

@ViewChild(ResultsComponent) resultsComponent: ResultsComponent; 

Search(){ 
    // alert(this.query) 
    //console.log(this.query); 
    localStorage.setItem('val',JSON.stringify(this.query)); 
    this.router.navigate(['/result']); 
    resultsComponent.open(); 
} 

结果组件:

constructor() { 
} 

open() { 
    this.query=JSON.parse(localStorage.getItem('val')); 
    this.httpService.searchGeneric(this.query,1).subscribe(
    data => { 
     this.Getspecs = data; 
    this.count=data['totalItems']; 
    } 
); 
} 
+0

可以请你告诉我如何保持依存性构造?用简单的例子? – maadi

+0

在你的代码中,我目前看不到需要依赖注入,但是如果你需要看看它是什么以及它是如何工作的,你可以参考angular io文档https://angular.io/guide/dependency-injection –

+0

ok 。不知何故,我已经从标题调用函数。它正在更新我的数据集,但不更新我的DOM?你有什么想法吗? – maadi

相关问题