杜林林 發表於 2019-7-31 15:12:00

angular路由事件

<p>Angular&nbsp;4检测路由变化,可以使用router.events来监听:</p>
<p>支持的事件类型:</p>
<ul>
<li>NavigationStart:导航开始</li>
<li>NavigationEnd:导航结束</li>
<li>NavigationCancel:取消导航</li>
<li>NavigationError:导航出错</li>
<li>RoutesRecoginzed:路由已认证</li>
</ul>
<p>在判断事件类型需要导入对应的事件类型,如:</p>
<pre><code>import&nbsp;{&nbsp;Router,&nbsp;NavigationStart&nbsp;}&nbsp;from&nbsp;'@angular/router';
</code></pre>
<p><strong>监听单一事件</strong></p>
<pre><code>this.router.events
&nbsp;&nbsp;.filter((event)&nbsp;=&gt;&nbsp;event&nbsp;instanceof&nbsp;NavigationEnd)
&nbsp;&nbsp;.subscribe((event:NavigationEnd)&nbsp;=&gt;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;//do&nbsp;something
});
</code></pre>
<p><strong>监听多个事件</strong></p>
<pre><code>constructor(router:Router)&nbsp;{
&nbsp;&nbsp;router.events.subscribe(event:Event&nbsp;=&gt;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;if(event&nbsp;instanceof&nbsp;NavigationStart)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//
&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;if(event&nbsp;instanceof&nbsp;NavigationEnd)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//
&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;if(event&nbsp;instanceof&nbsp;NavigationCancel)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//
&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;if(event&nbsp;instanceof&nbsp;NavigationError)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//
&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;if(event&nbsp;instanceof&nbsp;RoutesRecognized)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;});
}<br><br>运用实例参考:https://www.cnblogs.com/mary-123/p/10728614.html<br><br></code></pre><br><br>
来源:https://www.cnblogs.com/mary-123/p/11276454.html
頁: [1]
查看完整版本: angular路由事件