Angular2在路由上传递数据值

时间:2017-02-02 12:33:19

标签: angular angular2-routing angular2-forms

我正在尝试将数据从表单传递到服务,但没有成功。我设法在主页面和登录页面之间实现工作路由系统。我想将 LoginComponent 中的用户名和密码传递给VehicleService并显示当前的登录用户。我试过了:

  1. 创建LoginService以将数据传递给VehicleService。
  2. 以下是代码:

    路由器

    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    
    import { VehicleComponent } from './vehicle.component';
    import { LoginComponent } from './login.component';
    
    const routes: Routes = [
      { path: '', redirectTo: '/vehicle', pathMatch: 'full' },
      { path: 'vehicle', component: VehicleComponent },
      { path: 'login', component: LoginComponent }
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    

    VehicleService

    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    import { Md5 } from 'ts-md5/dist/md5';
    
    import { User } from './user';
    import 'rxjs/add/operator/map';
    
    @Injectable()
    export class VehicleService {
        private defUrl = 'dummywebiste.com';
    
        constructor(private http: Http) { }
        getVehicle(username?: string, password?: string) {
            const url = (!username || !password) ? this.defUrl : 'dummywebiste.com' + username + '/' + Md5.hashStr(password);
            return this.http.get(url)
                .map(res => res.json());
        }
    }
    

    简化 VehicleComponent

    @Component({
      selector: 'vehicle-json',
      templateUrl: './vehicle.html',
      providers: [VehicleService]
    })
    export class VehicleComponent {
      public vehicles: GeneralVehicle[];
    
      constructor(private vehicleService: VehicleService, private router: Router) {
        this.vehicleService.getVehicle().subscribe(vehicle => {
          this.vehicles = vehicle;
        });
      }
    
      toLogin(): void {
        console.log("toLogin button");
        this.router.navigate(['/login']);
      }
    }
    

    简化 LoginComponent

    @Component({
        selector: 'login',
        templateUrl: './login.html',
        providers: [VehicleService]
    })
    export class LoginComponent implements OnInit {
        public user: FormGroup;
    
        ngOnInit() {
            this.user = new FormGroup({
                username: new FormControl('', Validators.required),
                password: new FormControl('', Validators.required)
            });
        }
    
        constructor(public vehicleService: VehicleService, private location: Location, private router: Router) { }
    
        onSubmit(user) {
            this.vehicleService
                .getVehicle(user.value.username, user.value.password)
                .subscribe(user => {
                    this.user = user;
                    //this.user.reset();
                    this.router.navigate(['/vehicle']);
                    console.log("Submit button");
                });
        }
        goBack(): void {
            console.log("Back button");
            this.location.back();
        }
    }
    
    来自onSubmit()

    LoginComponent在我提交数据时未传递任何数据。当我使用一个没有路由系统的组件时,它很好。

    感谢。

1 个答案:

答案 0 :(得分:1)

当您登录时,您正在订阅LoginComponent

中的值
.subscribe(user => {
    this.user = user; // values are here
    this.router.navigate(['/vehicle']); // values lost when navigating away

因此,用户信息位于LoginComponent,但是您离开该组件的第二个用户信息正在丢失您的数据。要在会话期间存储它,您可以使用HTML localStorage,更多关于here的信息。

因此,在导航离开页面之前,请将用户设置为localStorage

.subscribe(user => {
    this.user = user; 
    localStorage.setItem('currentUser', JSON.stringify(this.user));
    this.router.navigate(['/vehicle']); 

然后在VehicleComponent中,您从localStorage中检索该数据并进行解析。我会在你的服务中添加I方法,如下:

getUser(): any {
    return JSON.parse(localStorage.getItem('currentUser'));
}

然后在VehicleComponent调用该方法并获取当前用户:

ngOnInit() {
  this.user = this.vehicleService.getUser();
}

然后,您可以访问VehicleComponent中的当前用户。

除了这个解决方案之外,还有一个共享服务选项可供您使用:Components communicate via service。但如果您不需要其他任何服务,那可能会有点过分。