Angularv4.初体验


1196 浏览 5 years, 3 months

19 详情搜索 Search Detail

版权声明: 转载请注明出处 http://www.codingsoho.com/

在前一节,我们实现了搜索提交的事情响应,但是在处理时只是打印了内容,一般我们需要跳转到对应的搜索页,本节将来完成这个功能。

首先引入导航功能,分三步

1.import router库
2.将该库在构造函数实例化
3.在函数出调用this.route.navigate()

import { Router } from '@angular/router'

constructor(private router:Router) { }

submitSearch(event, formData){
  console.log(event)
  console.log(formData.value)
  let query = formData.value['q']
  if(query){
      this.router.navigate(['/search', {q:query}])  
  }  
}

新的导航地址是/search,我们希望这个是一个新的页面,所以创建新的component search-detail来实现它

创建新模块

(env) E:\Computer\virtualenv\tryangular4\client>ng g component search-detail
CREATE src/app/search-detail/search-detail.component.html (32 bytes)
CREATE src/app/search-detail/search-detail.component.spec.ts (671 bytes)
CREATE src/app/search-detail/search-detail.component.ts (296 bytes)
CREATE src/app/search-detail/search-detail.component.css (0 bytes)
UPDATE src/app/app.module.ts (1278 bytes)

在app.routing.ts,导入新生成的这个模块,并且将它添加到routes里

import { SearchDetailComponent } from './search-detail/search-detail.component';
const appRoutes: Routes = [
  {
    path:"search",
    component:SearchDetailComponent,
  },  
]

再次执行搜索时,加入搜索内容”beach”, 那么它跳转到链接 http://localhost:4200/search;q=beach
网页显示内容search-detail works!,这个是初始默认,我们还没有处理这些parameter,接下来处理它

在文件search-detail.component.ts
1.导入ActivatedRoute
2.同样,在构造函数里实例化这个对象
3.OnInit函数里注册函数,处理navigate过来的参数内容
4.同时导入OnDestroy函数,在这个里面我们要释放前面注册的对象

import { ActivatedRoute } from '@angular/router'

export class SearchDetailComponent implements OnInit, OnDestroy {
  private routeSub:any;
  queryString;
  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
      this.routeSub = this.route.params.subscribe(params=>{
          console.log(params)
          this.query = params['q']
      })
  }

  OnDestroy() {
      this.routeSub.unsubscribe()
  }
}

参考前面this.router.navigate(['/search', {q:query}]),这个param对应的是{q:query}

简单修改search-detail.component.html文件来显示内容

<search class="text-center search-inline" *ngIf='!query'></search>

<p *ngIf='query'>
  Searched for <b>{{query}}</b>
</p>

这个地方添加了一个search-inline类属性,主要是为了让搜索结果显示跟前面的搜索组件显示一致。

文件styles.css

.search-inline .navbar-left{
    float: none!important;
}

http://localhost:4200/search;q=bearch

http://localhost:4200/search

至此,我们已经相应了对应内容的搜素及相应的显示,虽然显示的内容还是比较粗糙。

在上面的搜索过程中,导航条的搜索框并没有显示当前搜索内容,没有记忆功能,这个方面还需要提高一下,下一节来解决。