简体   繁体   English

ngOnInit() 被调用两次

[英]ngOnInit() being called twice

I want to make an update page by Angular 6 to first load data from webservice and establish it in the html form .我想通过Angular 6创建一个更新页面,首先从 webservice 加载数据并在 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我创建了一个resovler来处理异步数据加载,但是组件中的观察者总是返回 null,即使我可以看到 web 服务返回 200 并从浏览器以正确的格式提供所有数据,这里是代码片段

update更新

When running debug mode I found the ngOnInit() is called twice but resolver only called once.在运行调试模式时,我发现ngOnInit()被调用了两次,但resolver只调用了一次。

The first time ngOnInit() does provide the cart object but the next time cart object is null.第一次ngOnInit()确实提供了购物车对象,但下一次购物车对象为空。

I don't see any error from Angular console, nor in FireFox console我在 Angular 控制台和 FireFox 控制台中都没有看到任何错误

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

what is the problem?问题是什么?

I think its not ngOnInit() issue.我认为这不是ngOnInit()问题。 actually in debug mode service hit twice.实际上在调试模式下服务命中了两次。 for more detail please see this answer.有关更多详细信息,请参阅此答案。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM