I want to make an update page by Angular 6
to first load data from webservice and establish it in the html form
. I create a resovler
to handle the async data loading however the observer in the component always return null even though I can see the web service return 200 and provide all the data in correct format from browser, here is the code snippet
update
When running debug mode I found the ngOnInit()
is called twice but resolver
only called once.
The first time ngOnInit()
does provide the cart object but the next time cart object is null.
I don't see any error from Angular console, nor in FireFox console
Resolver
@Injectable({
providedIn: 'root'
})
export class CartResolver implements Resolve<ServiceCart> {
constructor(private service: CartService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const id = route.params['id'] ? route.params['id'] : null;
if (id) {
const existingCart = this.service.find(id).pipe(map((cart: HttpResponse<ServiceCart>) => cart.body));
return existingCart;
}
return of(new ServiceCart());
}
}
Router
const routes: Routes = [
{
path: '', component: CartComponent,
children: [
{path: '', redirectTo: 'list', pathMatch: 'full'},
{path: 'list', component: CartListComponent},
{path: 'create', component: CartEditComponent, resolve: {cart: CartResolver}},
{path: 'update/:id', component: CartEditComponent, resolve: {cart: CartResolver}}
]
}];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class CartRoutingModule {}
Component
@Component({
selector: 'app-cart-edit',
templateUrl: './cart-edit.component.html',
styleUrls: ['./cart-edit.component.css']
})
export class CartEditComponent implements OnInit {
cart: ServiceCart;
.....
ngOnInit() {
this.isSaving = false;
this.activatedRoute.data.subscribe(({ cart }) => {
this.cart = cart; // <--- always null
});
}
CartService (to handle RESTful service)
@Injectable({
providedIn: 'root'
})
export class CartService {
find(id: number): Observable<EntityResponseType> {
return this.http.get<ServiceCart>(`${this.environment.config.servicesBaseUrl + '/api/carts'}/${id}`,
{ observe: 'response' });
}
}
what is the problem?