@angular – 获取地址栏参数

路由之间传参

在网上找到一个不错的写的,分享给大家:

一般我们页面跳转传递参数都是这样的格式:

http://angular.io/api?uid=1&username=moon

但是在SPA单页应用中却是下面的结果居多【初级视频都是这样敷衍的】

http://angular.io/api/1/moon

一、 地址栏传参

实现从product页面跳转到product-detail页面

1:在app-routing.module.ts中配置路由。

const routes: Routes = [
{
    path: 'product',
    component: ProductComponent,
 },
 {
    path: 'product-detail',
    component: ProductDetailComponent,
  }
];

2:在app-routing.module.ts中配置路由。

constructor(
    private router: Router,   //这里需要注入Router模块
){}
 
jumpHandle(){
    //这是在html中绑定的click跳转事件
    this.router.navigate(['product-detail'], {
        queryParams: {
            productId: '1',
            title: 'moon'
        }
    });
}


3:在product-detail.ts中获取传递过来的参数productId、title

constructor(
    private activatedRoute: ActivatedRoute,   //这里需要注入ActivatedRoute模块
) {
    activatedRoute.queryParams.subscribe(queryParams => {
        let productId = queryParams.productId;
        let title = queryParams.title;
    });
}


二、 在查询中传递参数

 



//传递数据
<a [routerLink]="['/stock']" [queryParams]="{id: 1}">股票详情</a>
// http://localhost:4200/stock?id=1



// 接受参数
import { ActivatedRoute } from '@amgular/router';

export class StockComponent implements OnInit {

    private stockId: number;    
    
    constructor(private routeInfo: ActivatedRoute)
    
    ngOnInit() {
        this.stockId = this.routeInfo.snapshot.queryParams['id'];
    }
    
}

三、 在路径中传递参数

//修改配置
const routes: Routes = [
  {path: '', redirectTo: '/index', pathMatch: 'full'},
  {path: 'index', component: IndexComponent},
  {path: 'stock/:id', component: StocksComponent },
  {path: '**', component: ErrorPageComponent }
];


//传递数据
...
<a [routerLink]="['/stock', 1]">股票详情</a>
// http://localhost:4200/stock/1



//接受参数
...
import { ActivatedRoute } from '@amgular/router';

export class StockComponent implements OnInit {

    private stockId: number;    
    
    constructor(private activedRoute: ActivatedRoute)
    
    ngOnInit() {
        this.stockId = this.activedRoute.snapshot.params['id'];
    }
    
}

使用snapshot快照的方式传递数据,因为初始化一次,路由到自身不能传递参数,需要使用订阅模式。

this.activedRoute.params.subscribe((params: Params) => this.stockId = params['id']);

 

四、在路由中配置

//路由配置配置
const routes: Routes = [
  {path: '', redirectTo: '/index', pathMatch: 'full'},
  {path: 'index', component: IndexComponent, data: {title: 'Index Page'}},
  {path: 'stock/:id', component: StocksComponent, data: {title: 'Stock Page'}},
  {path: '**', component: ErrorPageComponent, data: {title: 'Stock Page'}}
];

//接受参数
this.title = this.routeInfo.snapshot.date[0]['title'];

发表评论

电子邮件地址不会被公开。 必填项已用*标注