使用路由器链接发送数据

时间:2017-12-13 13:06:37

标签: html angular webstorm

我正在尝试使用路由按钮中的[queryParams]="{'usd':usd, 'count' :country, 'name' :name}"将数据从一个页面传递到另一个路由页面。它完全正常,但我的控制台出错了。

ERROR in src/app/hairstylist-profile/hairstylist-profile.component.ts(18,40): error TS2339: Property 'value' does not exist on type 'Observable<Params>'.
src/app/hairstylist-profile/hairstylist-profile.component.ts(20,42): error TS2339: Property 'value' does not exist on type 'Observable<Params>'.
src/app/hairstylist-profile/hairstylist-profile.component.ts(22,41): error TS2339: Property 'value' does not exist on type 'Observable<Params>'.

这是我的代码:

import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-hairstylist-profile',
  templateUrl: './hairstylist-profile.component.html',
  styleUrls: ['./hairstylist-profile.component.css'],
})
export class HairstylistProfileComponent implements OnInit {
  name;
  usd;
  count;
  constructor(private  route: ActivatedRoute) {

  }

  ngOnInit() {
    const usd = this.route.queryParams.value.usd;
    this.usd = usd;
    const count = this.route.queryParams.value.count;
    this.count = count;
    const name = this.route.queryParams.value.name;
    this.name = name;
  }
}

关键字出错。那怎么解决?

2 个答案:

答案 0 :(得分:0)

这可以帮助你

ngOnInit() {
       this.route
               .queryParams
               .subscribe(params => {
                   // Defaults to 0 if no query param provided.
                 this.usd = params['usd'] || 0;
                 this.count = params['count'] || 0;
                 this.name = params['name'] || ';
                 });
}

您不能使用.value,您必须订阅查询parmas

答案 1 :(得分:0)

更新4.0.0

有关详细信息 https://angular.io/guide/router#fetch-data-before-navigating

,请参阅Angular文档

<强> ORIGINAL

使用服务是可行的方法。在路径参数中,您应该只传递要在浏览器URL栏中反映的数据。

另见 https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

RC.4随附的路由器重新引入data

constructor(private route: ActivatedRoute) {}

和..

const routes: RouterConfig = [
  {path: '', redirectTo: '/heroes', pathMatch : 'full'},
  {path : 'heroes', component : HeroDetailComponent, data : {some_data : 'some value'}}
];

和..

class HeroDetailComponent {
  ngOnInit() {
    this.sub = this.route
      .data
      .subscribe(v => console.log(v));
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}

另请参阅 https://github.com/angular/angular/issues/9757#issuecomment-229847781

上的Plunker