【发布时间】:2017-06-19 12:51:54
【问题描述】:
我正在尝试将数据从表单传递到服务,但没有成功。我设法在主页和登录页面之间实现工作路由系统。我想将用户名和密码从 LoginComponent 传递给 VehicleService 并显示当前登录用户。我试过了:
- 创建 LoginService 以将数据传递给 VehicleService。
代码如下:
路由器
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 { }
车辆服务
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']);
}
}
简化的登录组件
@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() from LoginComponent 在我提交数据时没有传递任何数据。当我使用一个没有路由系统的组件时,它很好。
谢谢。
【问题讨论】:
-
什么意思,onSubmit 方法没有被触发,或者您无法从表单中提取值?
-
..或者您是否希望在登录并导航到用户信息后会跟随车辆?您正在订阅 LoginComponent 中的值,因此值在那里,但是当您离开该组件时,您将失去用户。如果你想存储它以便它在应用程序中可用,你需要使用 localstorage 或 service 来存储用户值。
标签: angular angular2-routing angular2-forms