【问题标题】:ngOnInit() being called twicengOnInit() 被调用两次
【发布时间】:2019-04-04 03:09:17
【问题描述】:

我想通过Angular 6制作一个更新页面,首先从webservice加载数据并在htmlform中建立它。我创建了一个resovler 来处理异步数据加载,但是组件中的观察者总是返回 null,即使我可以看到 Web 服务返回 200 并从浏览器以正确格式提供所有数据,这里是代码 sn-p

更新

在运行调试模式时,我发现ngOnInit() 被调用了两次,而resolver 只被调用了一次。

第一次ngOnInit() 确实提供了购物车对象,但下一次购物车对象为空。

我在 Angular 控制台和 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' });
    }
}

有什么问题?

【问题讨论】:

标签: javascript angular


【解决方案1】:

我认为这不是ngOnInit() 的问题。实际上在调试模式下服务命中了两次。有关更多详细信息,请参阅此答案。

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

【讨论】:

  • 我同意另一个答案。你能用 console.log 或类似的东西验证它在 prod 和 debug 模式下发生吗?
猜你喜欢
  • 2023-04-10
  • 2021-11-25
  • 2019-12-04
  • 1970-01-01
  • 2017-02-20
  • 2020-05-27
  • 2017-07-30
  • 2016-04-01
相关资源
最近更新 更多