天天看點

從 Angular 中的 URL 擷取查詢參數

本文介紹了如何從 Angular 中的 URL 擷取查詢參數。

通過注入ActivatedRoute的執行個體,可以訂閱各種可觀察對象,包括queryParams和params observable。以下是範例:

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();
  }
}           

參考引用

繼續閱讀