服务函数被调用两次

时间:2017-06-17 16:21:40

标签: angular

我有身份验证组件

@Component({
    selector: "oe-authentication-view",
    templateUrl: "./authentication-view.component.html"
})
export class AuthenticationViewComponent implements OnInit {

    authorizationFormGroup: FormGroup;
    login: FormControl;
    password: FormControl;

    error: ErrorMessage;

    constructor(@Inject('IUserService') private _userService: IUserService,
                private _router: Router) {
        this.error = new ErrorMessage(Messages.CHECK_DATA_AND_TRY_AGAIN);
    }

    ngOnInit(): void {
        if (this._userService.userSession.isAuthenticated) {
            this._router.navigate([URI.COMPARISONS_RESOURCE]);
        }
        this.initForm();
    }

    private initForm() {
        this.login = new FormControl('', [
            Validators.required,
        ]);
        this.password = new FormControl('', [
            Validators.required,
            Validators.minLength(8)
        ]);
        this.authorizationFormGroup = new FormGroup({
            login: this.login,
            password: this.password
        });
    }

    onSubmit(): void {
        this._userService.authenticate(this.login.value, this.password.value).then((isAuthenticated: boolean) => {
            if (isAuthenticated) {
                let user: User = new User(this.login.value, this.password.value);
                this._userService.userSession = new UserSession(user, isAuthenticated);
                this._userService.fetchRole().then((role: Role) => {
                    this._userService.userSession.user.role = role;
                    this._router.navigate([URI.COMPARISONS_RESOURCE]);
                });
            } else {
                this.error.isError = true;
            }
        });
    }
}

,模板

<div class="container">
    <form class="form-sign" [formGroup]="authorizationFormGroup" novalidate (submit)="onSubmit()">
        <div class="greetings">
        </div>
        <div class="alert alert-danger" role="alert" *ngIf="error.isError">{{error.errorMessage}}</div>
        <input class="form-control" [ngClass]="{'form-control-danger': login.errors && login.touched}"
               placeholder="Login" type="text" formControlName="login" autofocus/>
        <input class="form-control" [ngClass]="{'form-control-danger': password.errors && password.touched}"
               placeholder="Password" formControlName="password" type="password"/>
        <button class="btn btn-lg btn-primary btn-block" type="submit" [disabled]="authorizationFormGroup.errors"
                (click)="onSubmit()">Sign in
        </button>
        <div class="forgot-password">
            <a href="#">Forgot password?</a>
        </div>
    </form>
</div>

和身份验证服务

@Injectable()
export class UserService implements IUserService {
    userSession: UserSession;

    constructor(private _http: Http) {
        this.userSession = new UserSession();
    }

    authenticate(username: string, password: string): Promise<Boolean> {
        let params: URLSearchParams = Endpoint.getPredefinedURLSearchParams();
        params.set("username", username);
        params.set("password", password);
        let url = Endpoint.BASE_URL
            + Endpoint.DELIMITER
            + Endpoint.AUTH_RESOURCE;
        return this._http.get(url, {search: params}).toPromise().then((res: Response) => res.json());
    }

    fetchRole(): Promise<Role> {
        let params: URLSearchParams = Endpoint.getPredefinedURLSearchParams();
        let url = Endpoint.BASE_URL
            + Endpoint.DELIMITER
            + Endpoint.USERS_RESOURCE
            + Endpoint.DELIMITER
            + this.userSession.user.login
            + Endpoint.DELIMITER
            + Endpoint.ROLE_RESOURCE;
        return this._http.get(url, {search: params}).toPromise().then((res: Response) => res.json());
    }
}

和将所有东西绑在一起的模块

@NgModule({
    imports: [
        BrowserModule,
        HttpModule,
        FormsModule,
        ReactiveFormsModule
    ],
    declarations: [
        AuthenticationViewComponent
    ],
    providers: [
        {provide: 'IUserService', useClass: UserService},
    ],
    bootstrap: [OutletComponent]

}) export class Module { }

然后单击提交按钮onSubmit()函数被调用。 由于某种原因,服务函数authenticate()和fetchRole()被调用两次。 发生了什么以及如何防止这种情况发生?

2 个答案:

答案 0 :(得分:1)

您在两个事件上设置了功能 onSubmit():按钮(单击)和表单(提交)。它会打两次电话。

def get_origin(self, obj):
    return obj.somelist.all()[ind]

答案 1 :(得分:1)

从按钮中删除(click)="onSubmit()"

 <button class="btn btn-lg btn-primary btn-block" type="submit" [disabled]="authorizationFormGroup.errors">