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

Aar*_*ron 0 javascript angular-routing angular

我的组件的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 -->
Run Code Online (Sandbox Code Playgroud)

页面加载时,立即调用submitSurvey,然后不断调用.这是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';
  }
Run Code Online (Sandbox Code Playgroud)

该方法立即开始服务并继续直到我终止服务器.在单击按钮之前,如何防止调用该函数?我是Angular的新手,我可能只是犯了一个新手的错误,如果是这样你也可以指出这一点.提前致谢.

Wil*_*han 5

[routerLink]是一个输入,请注意[].因此,Angular将立即解决该问题,并在每个更改检测周期内解决,以满足模板.您想要使用(click)哪个是输出,请注意()并且仅在单击按钮时调用.然后,而不是在submitSurvey()函数调用router.navigate()上返回url (首先注入路由器.)

HTML

<button class="btn btn-primary" (click)="submitSurvey()" routerLinkActive="active">Finish</button>
Run Code Online (Sandbox Code Playgroud)

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');
}
Run Code Online (Sandbox Code Playgroud)