Angular4 + Django1.11 vol.9
参考サイト
https://www.codingforentrepreneurs.com/projects/angular-django/
Catch All 404 + 500 Server Page
404 error, 500 error のときのページの処理を、angularのrouterを使って実装する。
HomeComponentのrouterの設定をpathMatch fullに設定する。
const appRoutes: Routes = [ { path:"", component: HomeComponent, pathMatch: 'full' // fullでpathがmatchしないとHomeComponentは起動しない }, ]
$ ng g component not-found
で、not-found componentを作成する。not-found.component.htmlのコードを修正する。
<div class="text-center"> <h1>404 - Page Not Found</h1> </div>
- app.routing.tsに、NotFoundComponentをimportして、routerを設定する。
import { NotFoundComponent } from './not-found/not-found.component'; const appRoutes: Routes = [ { path:"", component: HomeComponent, pathMatch: 'full' }, { path:"search", component: SearchDetailComponent, }, { path:"videos", component: VideoListComponent, }, { path:"videos/:slug", component: VideoDetailComponent, }, { path:"**", // **を2つにしておく。 component: NotFoundComponent, } ]
これで、routerで設定されていないページに遷移したときに、404errorが表示されるようになっていればOK!
500 errorは、サーバーサイドのerrorなので、djangoのtemplateに設定する。500.htmlを、templatesフォルダに作成する。
{% load static %} <!doctype html> <html> <head> <meta charset="utf-8"> <title>Try Angular + Django </title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <!-- index.html --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <link href="{% static 'ang/styles.bundle.css' %}" rel="stylesheet"/></head> <body> <div class="container"> <div class="row"> <div class="col-sm-12 text-center"> <h1>500 Server Error | しばらくたってから、再度アクセスしてください。</h1> </div> </div> </div> </body> </html>
まとめ
- 404errorは、angularのrouterで設定できる、500errorは、backend側で設定する。
- 404errorのときは、pathを
**
にする。