如何修复错误 - 类型"void"上不存在属性'subscribe'?



我在下面代码中的submit函数下创建一个单词为subscribe的登录表单时,遇到了这个错误。错误表明类型"void"上不存在属性"subscribe"。我该如何着手解决这个问题?代码如图所示:

登录组件.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthService } from '../auth.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginForm!: FormGroup;
isSubmitted=false;
results: any = false;
constructor(private formbuilder:FormBuilder, private authService: AuthService,
private router: Router) { }
ngOnInit() {
this.loginForm = this.formbuilder.group({
// email:['', [Validators.required, Validators.email]],
name: ['',Validators.required],
password: ['',Validators.required]
});
//loginForm.controls.email
//use getter property instead
//fc.email
}
get fc(){
return this.loginForm.controls;
}
submit(){
this.isSubmitted = true;
if(this.loginForm.valid)

this.authService.authUser(this.loginForm.value.name, 
this.loginForm.value.password).subscribe(data => { 
//error lies in line above(underlined subscribe)
this.results = data;
if (this.results[0].auth) 
{
this.authService.setSecureToken(this.loginForm.value.name);
this.router.navigateByUrl('/user');
} else{
console.log("Wrong username or password")
}
});
}
}

AuthUser功能:

authUser(username: string, pw: string) {
return this.http.post<any[]>(this.authuser, {
'username': username,
'password': pw
}),
console.log('user registered!')
}

您返回的是void,而不是前面提到的@Zero12n中的Observable。

您可以通过typeof(authUser())检查authUser()返回的数据类型。

为了返回一个可观察的,您不能在authUser()函数中调用subscribe。如果您确实需要做一些事情,可以使用rxjspipemap

例如:

authUser(usernameEmail: string, password: string): Observable<any> {
this.http.post<any>('auth', { usernameEmail, password }).pipe(
map((res) => {
this.usernameMessage = res.message;
return res.valid;
})
)
}

您应该在authService中显示authUser()的代码,但看起来它返回的是void,而不是Observable。修复authUser()中的代码,以便返回可观察的。我猜您正在进行HTTP调用,因此您不需要authUser中的subscribe()

------编辑------

您正在将authUser传递给authUser,我认为您不打算在这里进行递归调用。你应该把后端的url放在那里(一个字符串(

authUser(username: string, pw: string):Observable<any> {
return this.http.post(YOUR_URL_HERE, {
'username': username,
'password': pw
});
console.log('user registered!'); // This will never be called because it's after the "return"
}

最新更新