Angularv4.初体验


854 浏览 3 years, 10 months

21 视频服务 Video Service

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

要实现搜索功能,我们可以在video-detail或者video里实现,通过http,利用类似下面的方法获取等

  ngOnInit() {
    this.routeSub = this.route.params.subscribe(params => {
      // console.log(params);
      this.slug = params['slug']
      this.req = this.http.get("assets/json/videos.json").subscribe(data=>{
        data.json().filter(item=>{
          if(item.slug == this.slug){
            this.video = item
          }
        })
      })      
    }) 
  }

在这两个模块中的实现有很多相同之处,往往大部分时候只有微小的差异,这一节我们引入service功能来优化

创建app/videos/videos.service.ts

我们也可以用命令来创建

(env) E:\Computer\virtualenv\tryangular4\client>ng g service videos
CREATE src/app/videos.service.spec.ts (374 bytes)
CREATE src/app/videos.service.ts (135 bytes)

它会创建videos.service.spec.ts和videos.service.ts两个文件,这个里面包含了一些默认的内容,有些并不是必须的
并且它是放在app根目录下的,为了方便管理,我们还是把它移到app/videos目录下面

将以上两个文件从app/下面移到app/videos/下面

在videos.service.ts添加功能,list返了针对endpoint执行get操作的返回结果,这个endpoint可以是当前的asset下的json文件,将来也可以是远程访问链接
返回之后,下面代码又做了两步操作,map – 将结果转成json格式,catch – 捕获错误

import { Http } from '@angular/http';
import { map, filter, catchError, mergeMap } from 'rxjs/operators';

const endpoint = 'assets/json/videos.json' //http://www.youdomain.com/api/videos

export class VideoService {

  constructor(private http:Http) { }

  list(){
      return this.http.get(endpoint)
      .pipe(
           map(response=>response.json()), 
           catchError( this.handleError);
        )
  }

  private handleError(error:any, caught:any):any{
      console.log("handleError")
      console.log(error, caught)
  }
}

下面在videos-list使用这个功能

文件video-list.component.ts

原来用原始http实现时的部分代码如下

 import { Http } from '@angular/http';
constructor(private http:Http) { }

  ngOnInit() {
    this.todayDate = new Date()
     this.req = this.http.get("assets/json/videos.json").subscribe(data=>{
       console.log(data.json())
       this.videoList = data.json() as [any];
    })    
  }

将这个功能封装成service之后调用的格式如下

import { VideoService } from '../videos/videos.service'
@Component({
  providers: [VideoService]
})
constructor(private _video:VideoService) { }
  ngOnInit() {
    this.req = this._video.list().subscribe(data=>{
      console.log(data)
      this.videoList = data as [any];
    })    
  }

同样真多video-detail我们可以用类似的方法封装

将video-detail.component.ts里ngOnInit里的部分功能封装到videos.service.ts,get函数用于获取具体的video的信息

  get(slug){
      return this.http.get(endpoint).pipe(
        map(response=>{
          let data = response.json().filter(item=>{
            if (item.slug == slug) {
              return item
            }
          })
          if (data.length == 1){
            return data[0]
          }
          return {}
        }),
        catchError(this.handleError)
      )
   }

修改将video-detail.component.ts,将下列内容进行替换

import { Http } from '@angular/http';
constructor(private route: ActivatedRoute, private http:Http) { }
  ngOnInit() {
    this.routeSub = this.route.params.subscribe(params => {
      this.slug = params['slug']
      this.req = this.http.get("assets/json/videos.json").subscribe(data=>{
        data.json().filter(item=>{
          if(item.slug == this.slug){
            this.video = item
          }   
        })             
    }) 
  }

新的内容为

import { VideoService } from '../videos/videos.service'
@Component({
  providers: [VideoService]  
})
constructor(private route: ActivatedRoute, private _video:VideoService) { }
  ngOnInit() {
    this.routeSub = this.route.params.subscribe(params => {
      this.slug = params['slug']    
      this.req = this._video.get(this.slug).subscribe(data=>{
        this.video = data
      })      
    }) 
  }

函数返回默认是data?

Rxjs upgrade between angular5 & angular6

https://stackoverflow.com/questions/49811177/angular-6-rxjs-import-syntax

"rxjs": "^6.2.1", vs "rxjs": "^6.0.0",

https://stackoverflow.com/questions/50291570/module-not-found-error-cant-resolve-rxjs-add-operator-catch-in-f-angular

https://blog.ninja-squad.com/2018/05/04/what-is-new-angular-6/

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
export class VideoService {

  constructor(private http:Http) { }

  list(){
      return this.http.get(endpoint)
      .map(response=>response.json())
      .catch(this.handleError)
  }

在angular6更新为

import { map, filter, catchError, mergeMap } from 'rxjs/operators';
  list(){
      return this.http.get(endpoint)
      .pipe(
           map(response=>response.json()), 
           catchError( this.handleError);
        )
  }