我有一个service
正在使用http
post
request
到数据库。每当我在.ts
文件中使用它时,订阅该帖子后都不会发生任何事情。例如,该帖子有效,但之后的console.log
甚至没有执行。
login.ts
import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { AuthService } from 'src/app/services/auth-services';
import { LoadingController } from '@ionic/angular';
@Component({
selector: 'app-login',
templateUrl: 'login.page.html',
styleUrls: ['login.page.scss']
})
export class HomePage implements OnInit {
constructor(
public authService: AuthService,
public navCtrl: NavController,
public loadingCtrl: LoadingController,
) {}
email = '';
pw = '';
ngOnInit() {
}
login() {
this.authService.login(this.email, this.pw).subscribe(result => {
console.log('Valid User');
this.navCtrl.navigateForward('/menu/first/');
}, error => {
if (error.status === 401) {
console.log('Authorisation Required');
}
}
);
}
}
服务
import { Injectable } from '@angular/core';
import { HttpClient} from '@angular/common/http';
import { NavController, AlertController } from '@ionic/angular';
import { Observable } from 'rxjs';
let apiUrl = 'http://ccoulter12.lampt.eeecs.qub.ac.uk/api/';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(
private http: HttpClient,
public navCtrl: NavController,
public alertCtrl: AlertController,
) { }
login(emailin, pwin): Observable<any> {
const data = {
email: emailin,
pw: pwin
};
return this.http.post<any>(apiUrl + 'login.php', JSON.stringify(data));
}
}
答案 0 :(得分:0)
尝试一下:-
login() {
return this.authService.login(this.email, this.pw).subscribe({
next(result) {
this.presentLoading();
// store jwt
// move to dashboard
console.log('Valid User');
this.navCtrl.navigateForward('/menu/first/tabs/tab1');
}, error(error) {
if (error.status === 401) {
console.log('Authorisation Required');
}
}
});
}
答案 1 :(得分:0)
在控制器上,您将登录功能更改为:
login() {
this.authService.login(this.email, this.pw);
}
在AuthService中,将登录功能更改为:
apiUrl = 'http://ccoulter12.lampt.eeecs.qub.ac.uk/api/';
login(emailin: string, pwin: string) {
const data = {
email: emailin,
pw: pwin
};
this.http.post(this.apiUrl + 'login.php', JSON.stringify(data)).subscribe(result => {
console.log('Valid User');
}, error => {
if (error.status === 401) {
console.log('Authorisation Required');
}
}
);
}
在组件中,注入服务并调用其方法,同时在请求中直接订阅服务。此解决方案工作正常。服务器返回我403错误。
如果将参数传递给方法,请指定类型,如果不知道,请输入“ any”