Angular4入門_Vol.4
参考サイト
https://www.codingforentrepreneurs.com/projects/try-angular-v4/
Dynamic Routing of Components
- video-detail.component.tsにコードを追記する。
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'video-detail', templateUrl: './video-detail.component.html', styleUrls: ['./video-detail.component.css'] }) export class VideoDetailComponent implements OnInit { constructor(private route: ActivatedRoute) { } // instanceが作成されたときに自動でrouteのアノテーションを実行するぽい。 ngOnInit() { this.route.params.subscribe(params => { console.log(params) //subscribeは、変更があったときに、その変更を受取るメソッドのこと?なんであんまり解説がないんだろう。。。 }) // 上記のarrow関数は、以下と同じ意味 // this.route.params.subscribe(function(params){ // console.log(params) //}) } }
- video-list.component.html の、href部分を修正する。
<p> {{ title }} </p> <p *ngFor='let item of videoList'> <a href="videos/{{ item.slug }}" *ngIf='item.slug == "item-1"'>{{ item.name }}</a> <a href="videos/{{ item.slug }}" *ngIf='item.slug != "item-1"' style='color:red;'>{{ item.name }}</a> </p>
無事routingが機能した!console.logにparams objectも表示された。
video-detail.component.tsにさらにコードを追記する。subscribeの解放と、slug変数の設定をする。
import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'video-detail', templateUrl: './video-detail.component.html', styleUrls: ['./video-detail.component.css'] }) export class VideoDetailComponent implements OnInit, OnDestroy { private routeSub:any; //routeSub 変数をany で作成する slug: string; // slugをstringとして定義する。 constructor(private route: ActivatedRoute) { } ngOnInit() { // データバインドされた入力値を初期化後に実行される。 this.routeSub = this.route.params.subscribe(params => { console.log(params) this.slug = params['slug'] //this.slugに、paramsオブジェクトのslug のvalueを代入する。 }) } ngOnDestroy(){ //ngOnDestroyは、ディレクティブ・コンポーネントを破棄する前に呼ばれる。 this.routeSub.unsubscribe() //routeSubのsubscribeを解除する。unsubscribe } }
- video-detail.component.htmlに追記する。
<p> {{ slug }} video-detail works! </p>
まとめ
subscribeがふわっとしてる。subscribeは3つの引数を取り、subscribe(success, error, complete)とのことらしいので、ここでは、successのときの処理を書いたという感じか。subscribeは、特定のurlにアクセスして、その時の結果に応じて処理を変更できるということにしておくか。
unsubscribeは、subscribeを解除するために設定するらしい。メモリーを開放するとかそういう意味があるぽい。
ngOnInit, ngOnDestroyなどのライフサイクルはなんとなくしか理解してないので、ここを理解するのは重要かもしれんな。。。
privateと、publicの違いもよくわからんけど、たぶん、外に表示しないものは、privateで、それ以外はpublicというざっくりした認識でいいのかな。