代码之家  ›  专栏  ›  技术社区  ›  Dreamer

ngOnInit()被调用两次

  •  2
  • Dreamer  · 技术社区  · 7 年前

    我想通过 Angular 6 首先从webservice加载数据并在html中建立它 form . 我创造了一个 resovler 为了处理异步数据加载,但是组件中的观察者总是返回null,即使我可以看到web服务返回200并从浏览器中以正确的格式提供所有数据,下面是代码片段

    更新

    ngOnInit() 两次被叫来但是 resolver 只打过一次电话。

    恩戈尼特() 提供cart对象,但下次cart对象为空。

    我看不到任何来自角度控制台的错误,也看不到FireFox控制台的错误

    @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());
      }
    }
    

    路由器

    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({
      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(处理RESTful服务)

    @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' });
        }
    }
    

    怎么了?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Farhat Zaman    7 年前
    推荐文章