Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Angular4 + Django1.11 vol.8

参考サイト

https://www.codingforentrepreneurs.com/projects/angular-django/ https://angular.io/docs/ts/latest/guide/server-communication.html http://qiita.com/kura07/items/c9fa858870ad56dfec12

Handle Angular Http Error

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http'; //Responseをimportする

import { Observable } from 'rxjs/Observable'; //Observableをimportする

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';


// const endpoint = '/static/ang/assets/json/videos.json' // http://www.yourdomain.com/api/videos/
const endpoint = '/api/videos/'

@Injectable()
export class VideoService {
  constructor(private http: Http) { }

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

  featured(){
      return this.http.get(endpoint + "featured/")
              .map(response=>response.json())
              .catch(this.handleError)
  }

  get(slug){
    return this.http.get(endpoint + slug + "/")
            .map(response=>response.json())
            .catch(this.handleError)
  }

  search(query){
    let querystring = `?q=${query}`
    return this.http.get(endpoint + querystring)
            .map(response=>response.json())
            .catch(this.handleError)
  }

  // 以降はangularの公式ページからそのままコピペする。
  private handleError (error: Response | any) {
    // In a real world app, you might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }


  // private handleError(error:any, caught:any): any{
  //     // console.log(error, caught)
  //     if (error.status == 404){
  //       alert("Oopps. Not found")
  //     } else {
  //       alert("何かのミスが出てます。URLの確認をお願いします。")
  //     }
  // }

}
  • このままだと、TypeError: u.Observable.throw is not a functionが表示されるので、修正する。
import { Observable } from 'rxjs/Rx';
  • video-detail.component.ts, videos-detail.component.html をerrormessageを表示させるように少し修正する。
export class VideoDetailComponent implements OnInit, OnDestroy {
    private routeSub:any;
    private req:any;
    video: VideoItem;
    slug:string;
    errorStr: string; // errorStrに修正する。
  constructor(private route: ActivatedRoute, private router: Router, 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 as VideoItem
          }, error=>{
              console.log(error)
              this.errorStr = error; //errorStrにerrorを代入する
              // this.router.navigate(['/videos'])
          })
      })
  }
}
<div *ngIf='!video && !errorStr'>Loading</div>
<div *ngIf='errorStr'>{{ errorStr }}</div>
  • 404 - Not Found {"detail":"Not found."}のような感じで表示されればOK。ただ、{"detail":"Not found."}の部分は不要なので、handleErrorの、${err}の部分は削除しておく。

まとめ