本文介紹瞭如何從 Angular 中的 URL 獲取查詢參數。css
經過注入ActivatedRoute的實例,能夠訂閱各類可觀察對象,包括queryParams和params observable。如下是範例:html
import { ActivatedRoute } from '@angular/router'; // 用於獲取路由參數 import { Component, OnInit } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; // 用於HTML過濾 import { Location } from '@angular/common'; // 用於回退瀏覽記錄 import { NewsDetailService } from '../news-detail.service'; @Component({ selector: 'app-news-detail', templateUrl: './news-detail.component.html', styleUrls: ['./news-detail.component.css'] }) export class NewsDetailComponent implements OnInit { newsDetailData = null; newsUrl = null; constructor(private newsDetailService: NewsDetailService, private domSanitizer: DomSanitizer, private route: ActivatedRoute, private location: Location) { } ngOnInit() { this.showNewsDetailData(); } // 展現新聞詳情數據 showNewsDetailData() { this.route.queryParams.subscribe(p => { this.newsUrl = p.newsUrl // 獲取參數 this.newsDetailService.getNewsData(this.newsUrl).subscribe( (newsApiData) => this.newsDetailData = this.domSanitizer.bypassSecurityTrustHtml(newsApiData.toString()) //HTML過濾 ); }); } // 返回 goback() { // 瀏覽器回退瀏覽記錄 this.location.back(); } }