Angular 7,Ngrx,ExpressionChangedAfterItHaHasBeenCheckedError

时间:2019-06-19 08:41:07

标签: javascript angular typescript ngrx

寻找了较长时间,但找不到任何东西。

我有一个像这样的模板:

<learning-navigation *ngIf="(_navigationSelectedSafe$ | async) == _navigationLayout.location" [(selectMode)]="_navigationModeSelected"></learning-navigation>

位置:

private _navigationSelected$: Observable<string>;
private _navigationSelectedSafe$ = new EventEmitter<any>(true);

...

this._navigationSelected$.subscribe(res => {
  ...
  this._navigationSelectedSafe$.emit(res)
});

将学习导航的输入作为设置器:

  @Input()
  set selectMode(mode: number) {
    this.mode = mode;
  }

这会导致错误:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'selectMode: null'. Current value: 'selectMode: 1'. 

我已经尝试将EventEmitter更改为BehaviourSubject,在ngInit和ngAfterChecked之后强制detectChanges()(尽管即使可行,这也不是最佳选择),也将其包装在容器中以尝试将模式直接异步传递到该组件,同时仅通过额外的if控制显示。

当前解决方案有效,并且似乎没有任何副作用,但是无论每次模式更改,它都会引发错误。谢谢

2 个答案:

答案 0 :(得分:3)

您的问题表明Angular的更改检测范围之外存在值的更改。发生这种情况有多种原因。在您的情况下,我想这是您输入的异步性质。

如果您的组件是演示组件,则可以将更改检测策略设置为onPush

这样,您的变更检测器将仅在输入中包含新值时运行

示例:

@Component({
  selector: 'app-your-comp',
  templateUrl: './app-your-comp.component.html',
  styleUrls: ['./app-your-comp.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

答案 1 :(得分:0)

public function userlogin(Request $request){
    $validatedData = $request->validate([
                        'email' => 'required|max:255',
                        'pwd'   => 'required|max:255|min:3',
                        ]);

    $data = [   "username"=>$request->email,
                "password"=>$request->pwd,
            ]; 

    $ch = curl_init("http://localhost/getuus/login");           

    curl_setopt($ch, CURLOPT_POSTFIELDS,  json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    $result = collect(json_decode($result));

    if ($result['status'] == 1) {
        $Auth = new Auth;   $Auth::login($request, true);
        return redirect('home');           
    }
    else{

        return view('userlogin');
    }

}

这将防止在您的observable的值为null时显示<ng-container *ngIf="_navigationSelectedSafe$ | async as selectedSafe"> <learning-navigation *ngIf="selectedSafe == _navigationLayout.location" [(selectMode)]="_navigationModeSelected"></learning-navigation> </ng-container> 元素frop,从而消除错误。

编辑

在设置器中使用超时来解决任何进一步的问题:

learning-navigation