我想将 LoginComponent 的用户名和密码传递给VehicleService并显示当前的登录用户 . 我试过了:
- 创建LoginService以将数据传递给VehicleService .
这是代码:
Router
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 回答
登录时,您正在订阅
LoginComponent
中的值:因此,用户信息位于
LoginComponent
中,但是您离开该组件的第二个用户信息正在丢失您的数据 . 要在会话期间存储它,您可以使用HTMLlocalStorage
,更多关于here .因此,在导航离开页面之前,请将用户设置为
localStorage
:然后在
VehicleComponent
中从localStorage中检索该数据并解析它 . 我会在你的服务中添加我的方法,如下:然后在你的
VehicleComponent
调用该方法并获取当前用户:然后,您可以访问
VehicleComponent
中的当前用户 .除了这个解决方案之外,还有一个共享服务选项可以为您服务:Components communicate via service . 但如果您不需要其他任何服务,那可能会有点矫枉过正 .