将数据传递给Router Angular 2

时间:2017-06-09 11:20:43

标签: angular

我需要将数据传递给我的路由器以在目标组件中使用它,我使用了NavigationExtras' s QueryParam但是它显示了URL中的参数,还有其他方法可以传递数据?

let navigationExtras: NavigationExtras = {
            queryParams: {
                "param1": true,
            }
        };
        this.router.navigate(['/page1/view'],navigationExtras);

3 个答案:

答案 0 :(得分:1)

您好试试这样的事情:

1 - 声明服务,如:

import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';


@Injectable()
export class SharedService {

  // Observable sources (change activity)
    private emitChangeActivitySource = new Subject<any>();
    // Observable streams (change activity)
    changeActivityEmitted$ = this.emitChangeActivitySource.asObservable();
    // Service (change activity)
    emitChangeActivity(change: any) {
        this.emitChangeActivitySource.next(change);
    }

}

2-然后当你想获得(订阅)它时:

import {  SharedService } from '../shared/services/index';

@Component({
    selector: 'app-dashboard',
    templateUrl: './full-layout.component.html',
    styleUrls: ['./full-layout.component.scss']
})
export class FullLayoutComponent {


    constructor(private toasterService: ToasterService,
        private currentUserService: CurrentUserService,
        private menuService: MenuService,
        private router: Router,
        private auth: AuthService,
        private _sharedService: SharedService,
        private _activitiesService: ActivitiesService,
        private _router: Router) {


   _sharedService.changeActivityEmitted$.subscribe(
            activity => {
                this.data = activity;

                }
            });

            }

            }

3-您想要触发它的地方:

this._sharedService.emitChangeActivitySource({name:'',descr:''});

答案 1 :(得分:1)

正如其他人所说,使用服务。

我在这里有一个简单的示例:

https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

import { Injectable } from ‘@angular/core’;
@Injectable() 
export class DataService { 
  serviceData: string; 
}

现在在Angular v6及更高版本中:

import { Injectable } from ‘@angular/core’;
@Injectable({
   providedIn: 'root'
}) 
export class DataService { 
  serviceData: string; 
}

答案 2 :(得分:0)

在导航到下一页之前,使用set方法设置参数。然后导航到下一页

myFunction1(){
    this.uploadData = param;
    this.router.navigate(['/page1/view'])
}

set uploadData (param) {
        this._param = param;
}

进入下一页后,使用get方法

检索参数
myFunction2(){
        parameter = this.uploadData;
}   

get uploadData () {
            return this._param;
}
请注意。这只是一个sudo代码。您需要根据您的要求实施它。

您可以通过以下链接获取有关getter和setter的更多信息

set method

get method