routerlink = "functionName()" 在页面加载时立即调用

routerlink = "functionName()" invoked immediately upon page load

我的组件html是这样的:

<div id="summary">
  <div *ngFor="let question of thisSurvey">
    <div>
      <span class="badge">#{{question.questionNumber}}</span>
      <span>{{question.questionText}}</span>
    </div>
    <p>Your answer: {{question.questionAnswer}}</p>
  </div>
</div>
<br/>

<button class="btn btn-danger yes-no-btn" routerLink="/survey">Go Back</button>
<button class="btn btn-primary" [routerLink]="submitSurvey()" routerLinkActive="active">Finish</button> <!-- Issue here -->

页面加载时,立即调用 submitSurvey,然后不断调用。这是提交调查:

  // Send the answers back to the api for processing
  submitSurvey() {
    // Make sure everything is answered
    const allOKClientSide: boolean = this.surveyService.checkEntireForm(this.thisSurvey);

    if (allOKClientSide) {
       if (this.surveyService.checkFormOnline(this.thisSurvey).subscribe()) {
        return '/placeOne';
       }
    }

    return '/placeTwo';
  }

该方法立即开始命中服务并一直持续到我终止服务器。如何在单击按钮之前不调用函数?我是 Angular 的新手,可能只是犯了一个菜鸟错误,如果是的话,您也可以指出来。提前致谢。

您希望在单击按钮时调用您的方法。您可以使用 (clicK):

而不是

[routerLink]="submitSurvey()"

(click)="submitSurvey()"

然后你使用class中的路由器进行导航:

constructor(private router: Router) {}

submitSurvey() {
    // ...
    this.router.navigate(['/placeOne']);
}

[routerLink]是一个Input,注意[]。所以 Angular 将在每个变更检测周期立即解决这个问题,以满足模板。你想使用 (click) 这是一个输出,注意 () 并且只会在单击按钮时调用。然后,而不是在 submitSurvey() 函数调用 router.navigate() 上返回 url(首先注入路由器。)

html

<button class="btn btn-primary" (click)="submitSurvey()" routerLinkActive="active">Finish</button>

ts

constructor(private router: Router) { }

public submitSurvey(): void {
  // Make sure everything is answered
  const allOKClientSide: boolean = this.surveyService.checkEntireForm(this.thisSurvey);

  if (allOKClientSide) {
    if (this.surveyService.checkFormOnline(this.thisSurvey).subscribe()) {
      this.router.navigateByUrl('/placeOne');
      return;
    }
  }

  this.router.navigateByUrl('/placeTwo');
}