I'm trying to pass data from form to service, but with no success. I managed to implement working routing system between main page and login page. I'd like to pass username and password from LoginComponent to VehicleService and display currently logon user. I tried:
- Create LoginService to pass data to VehicleService.
Here's the code:
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());
}
}
Simplified 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']);
}
}
Simplified 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() from LoginComponent doesn't pass any data when I submit the data. When I was using one Component w/o routing system, it was fine.
Thanks.