首页 > 解决方案 > 角度传递值到 index.html

问题描述

我正在尝试将一个值传递给 index.html ,它调用 app.componenet。在进行重定向之前,我正在尝试处理在我的根组件中传递的查询字符串

链接目标

http://localhost:4200/index/1

HTML

  <app-root></app-root>

APP.组件

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [AppComponentService]
})

export class AppComponent {
 constructor(elm: ElementRef,private _service: AppComponentService, private _rout: ActivatedRoute) {

        this._rout.params.subscribe(params => {

            console.log('id' + params['id']);//value is undefined


        });
}

应用程序路由

{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },

*****************************更新******************** ******************************************************

我的问题应该来自溃败..请记住,在我重定向到仪表板之前,我试图先点击 app.comonent 以执行一些逻辑

I change my rout to

const routes: Routes = [
    { path: '', component: AppComponent }
];

@NgModule({
    imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })],
    exports: [RouterModule]
})

export class AppRoutingModule { }

应用程序组件

constructor(elm: ElementRef,private _service: AppComponentService, private _rout: ActivatedRoute) {

        this._rout.params.subscribe(params => {

            console.log('id' + params['id']);//value is undefined
             //some logic then will redirect to dashboard

        });

标签: angulartypescriptroutingroutes

解决方案


以下是如何根据 URL 获取 app.component.ts 中的参数。

即,http://localhost:4200/index/1

 export class AppComponent {
      constructor(private router: Router) {
        this.router.events.subscribe( (event: RouterEvent) => {
          if(event.url.startsWith('/index/')){
            console.log("id is %s", event.id);
            this.router.navigate(['/']);
          }

        });
      }

    }

如果要加载静态全局变量,可以使用路由数据对象传递

前任:

{ path: '', redirectTo: '/dashboard', pathMatch: 'full', data : {'one':'1', 'two': '2'} },

然后你可以得到如下的数据对象

export class AppComponent {

       constructor(private router: Router) {
           this.router.events.subscribe( (event: RouterEvent) => {
             console.log(event['snapshot'].data)      
           });
       }

}

推荐阅读