【问题标题】:How to show Angular components based on the value of query string?如何根据查询字符串的值显示 Angular 组件?
【发布时间】:2017-12-27 17:34:08
【问题描述】:

我目前使用的是 Angular 4/5,假设我有 2 个组件 Component 1Component 2。现在,我得到了一个任务,如果 URL 是http://localhost:4200/?property1=value1,则显示组件 1,如果 URL 是 http://localhost:4200/?property1=value2,则显示组件 2。

由于我是 Angular 的初学者,因此我在这两个任务中遇到了问题。

  1. 每次从查询字符串中查找property1的值(即value1和value 2)。

  2. 找到值后,如何定义逻辑,即显示哪个组件?

虽然我找到了这个link,但我找不到使用该值查看组件的逻辑。请帮忙。

编辑:在处理@Osman Cea 的答案时,这是我得到的错误:

null: ERROR
null: Error: StaticInjectorError[ActivatedRoute]: 
__zone_symbol__currentTask: ZoneTask {_zone: Zone, runCount: 0, _zoneDelegates: null, …}
message: "StaticInjectorError[ActivatedRoute]: 
  StaticInjectorError[ActivatedRoute]: 
    NullInjectorError: No provider for ActivatedRoute!"
ngDebugContext: DebugContext_ {view: Object, nodeIndex: 1, nodeDef: Object, …}
ngErrorLogger: function () { … }
ngTempTokenPath: null
ngTokenPath: Array(1) []
stack: "Error: StaticInjectorError[ActivatedRoute]: 
  StaticInjectorError[ActivatedRoute]: 
    NullInjectorError: No provider for ActivatedRoute!
    at _NullInjector.get (webpack-internal:///../../../core/esm5/core.js:1189:19)
    at resolveToken (webpack-internal:///../../../core/esm5/core.js:1477:24)
    at tryResolveToken (webpack-internal:///../../../core/esm5/core.js:1419:16)
    at StaticInjector.get (webpack-internal:///../../../core/esm5/core.js:1290:20)
    at resolveToken (webpack-internal:///../../../core/esm5/core.js:1477:24)
    at tryResolveToken (webpack-internal:///../../../core/esm5/core.js:1419:16)
    at StaticInjector.get (webpack-internal:///../../../core/esm5/core.js:1290:20)
    at resolveNgModuleDep (webpack-internal:///../../../core/esm5/core.js:11074:25)
    at NgModuleRef_.get (webpack-internal:///../../../core/esm5/core.js:12306:16)
    at resolveDep (webpack-internal:///../../../core/esm5/core.js:12804:45)"
__proto__: Object {constructor: , name: "Error", message: "", …}
null: ERROR CONTEXT
null: DebugContext_ {view: Object, nodeIndex: 1, nodeDef: Object, elDef: Object, elView: Object}
component: null
componentRenderElement: app-root
context: null
elDef: Object {nodeIndex: 0, parent: null, renderParent: null, …}
elOrCompView: Object
elView: Object {def: Object, parent: null, viewContainerParent: null, …}
injector: Injector_
nodeDef: Object {nodeIndex: 1, parent: Object, renderParent: Object, …}
nodeIndex: 1
providerTokens: Array(1)
references: Object
renderNode: app-root
view: Object {def: Object, parent: null, viewContainerParent: null, …}
__proto__: Object {elOrCompView: <accessor>, injector: <accessor>, component: <accessor>, …}
null: Error: StaticInjectorError[ActivatedRoute]:

【问题讨论】:

    标签: angular angular2-routing query-string angular-routing angular5


    【解决方案1】:

    您可以通过在父组件中注入 ActivatedRoute 并订阅它来获取您的 queryParams Observable 的引用。假设您有以下app.component.ts

    import { ActivatedRoute } from '@angular/router';
    @Component({
      template: `
        <ng-container [ngSwitch]="activeParam">
          <component-one *ngSwitchCase="'value1'"></component-one>
          <component-two *ngSwitchCase="'value2'"></component-two>
        </ng-container>
      `
    })
    export class AppComponent {
      activeParam: string;
    
      constructor(private route: ActivatedRoute) {
        this.route.queryParams.subscribe(params => this.activeParam = params.property1)
      }
    }
    

    您在params 参数中得到的是一个普通的常规对象,具有以下签名{ [key: string]: any } 其中key 是参数的名称,而值......嗯,给定参数的值。您可以在 activeParam 属性中获取该值,并使用 ngSwitch 指令来决定要渲染哪个组件。

    您也可以使用 Observables 和 async 管道来执行此操作,如下所示:

    import { ActivatedRoute } from '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import { pluck } from 'rxjs/operators';
    @Component({
      template: `
        <ng-container [ngSwitch]="activeParam$ | async">
          <component-one *ngSwitchCase="'value1'"></component-one>
          <component-two *ngSwitchCase="'value2'"></component-two>
        </ng-container>
      `
    })
    export class AppComponent {
      activeParam$: Observable<string>;
    
      constructor(private route: ActivatedRoute) {
        this.activeParam$ = this.route.queryParams.pipe(pluck('property1'))
      }
    }
    

    在这种情况下,您提取在订阅 observable 时获得的对象中分配给 property1 键的值,这样它会安全地忽略那些 queryParams 你没有t 实际上需要观察,并且 Observable 的 value 将是 value1value2,或者在您的 url 中 = 之后的任何内容。

    【讨论】:

    • 这两种方法都对我不起作用,因为每当我尝试打开链接 localhost:4200/?property1=value1 或带有 value2 的链接时,我都会得到 Error: StaticInjectorError[ActivatedRoute]。如何解决此错误?
    • 我已经在问题中发布了完整的错误消息跟踪。请看。
    • 我猜这是因为你必须将RouterModule 导入到你的主AppModule
    • 我在我的 AppModule 中将 RouterModule 导入为RouterModule.forRoot(routes),代码运行成功。但是我无法理解的一件事是,为什么它甚至可以将空数组路由提供为const routes: Routes = [ ];。你能解开我的这个疑问吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多