Djangoroidの奮闘記

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

Angular4 + Django1.11 vol.7

参考サイト

https://www.codingforentrepreneurs.com/projects/angular-django/ http://qiita.com/kura07/items/c9fa858870ad56dfec12

Handling 404 with Object Lookups

  • 指定したurlが無いときの、404 errorのページを設定する。

  • video-detail.component.ts を修正する。

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=>{ // subscribeがrrorの場合の内容をconsole.logに表示する
            console.log(error) //
        })
    })
}
  • 実際にerrorが出るpageにアクセスしてみると以下のようなerrorがconsoleに表示される。
eaders:t
ok:false
status:404
statusText:"Not Found"
type:2
url:"http://127.0.0.1:8000/api/videos/bound-method-videotitle-/"
_body:"{"detail":"Not found."}"
  • videos.service.ts にalertが出るように追記する。
private handleError(error:any, caught:any): any{
    console.log(error, caught)
    if (error.status == 404){ // statusが、404のときに、alertが表示されるように設定する
      alert("Oopps. Not found")
    }
}
  • さらに、errorがでたときには、video一覧に戻るようにrouterを設定する。設定するのは、video-detail.component.typescript.
import { ActivatedRoute, Router } from '@angular/router'; // Routerをimport
import { VideoItem } from '../videos/video';
import { VideoService } from '../videos/videos.service';
...
...
  constructor(private route: ActivatedRoute, private router: Router, private _video:VideoService) { }
  // constructorにprivate router: Routerで型定義する。

  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.router.navigate(['/videos']) // subscribeがerrorのときに、/videos にアクセスする。
          })
      })
  }
  • errorのときの処理をさらに修正する。
export class VideoDetailComponent implements OnInit, OnDestroy {
    private routeSub:any;
    private req:any;
    video: VideoItem;
    slug:string;
    error: Boolean; //errorの型定義をする
  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.error = true; // errorがでたときには、errorをtrueにする。
              // this.router.navigate(['/videos'])
          })
      })
  }
}
  • video-detail.component.htmlに追記する。
<div *ngIf='!video && !error'>Loading</div>
<div *ngIf='error'>Error. Please try again.</div>

まとめ

  • errorは、subscribeのerror時の処理を使うと良さそう。