1. 程式人生 > >從 Angular 中的 URL 獲取查詢引數

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

參考引用