2

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?

Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
Dreamer
  • 7,333
  • 24
  • 99
  • 179

1 Answers1

1

I think its not ngOnInit() issue. actually in debug mode service hit twice. for more detail please see this answer.

https://stackoverflow.com/a/36353822/7541317

Farhat Zaman
  • 1,339
  • 10
  • 20
  • i agree with the other answer. could you verify it happens in prod and debug mode with a console.log or something like that? – JBoothUA Oct 31 '18 at 04:23