首页 > 解决方案 > 解决不是一个功能

问题描述

在我的 ionic v4/angular 项目中,我创建了一个服务来调用 API。
该服务在添加授权标头之前getpost添加授权标头等之前执行一些操作。

@Injectable({
    providedIn: 'root'
})
export class ApiService {
    headers: HttpHeaders;

    constructor(private http: HttpClient,
                private storage: Storage,
                private loadingController: LoadingController,
                private alertController: AlertController,
                private router: Router) {
        this.storage.get('token').then(token => {
            this.headers = new HttpHeaders().set('Authorization', 'Bearer ' + token);
        });
    }

    async get<T>(url: string): Observable<T> {
        return this.init().then(async () => {
            this.http.get<T>(environment.api_url + url, {headers: this.headers}).subscribe(res => {
                return res;
            }, async err => {
                await this.checkError(err);
            });
        });
    }

    async post<T>(url: string, data: any): Observable<T> {
        return this.init().then(() => {
            this.http.post<T>(environment.api_url + url, data, {headers: this.headers}).subscribe(res => {
                return res;
            }, async err => {
                await this.checkError(err);
            });
        });
    }

    async checkError(err) {
        // if (err.status === 401) { }
        // if (err.status === 500) { }
        await this.alertController.create({
            header: 'Error',
            message: 'Sorry, Something bad happend on our side.',
            buttons: ['Ok']
        }).present();
    }

    async init() {
        const loading = await this.loadingController.create({
            spinner: 'crescent',
            message: 'Please Wait...'
        });

        await loading.present();
        // do some checking like version, connection, ...
        await loading.dismiss();
    }
}

但是当我订阅post此服务的方法时,我收到此错误:resolve is not a function

login(loginData:any) {
    this.api.post('/auth/login', loginData).subscribe(res => { });
}

标签: angularionic4

解决方案


我设法像这样解决了我的问题:

@Injectable({
    providedIn: 'root'
})
export class ApiService {
    headers: HttpHeaders;

    constructor(private http: HttpClient,
                private storage: Storage,
                private loadingController: LoadingController,
                private alertController: AlertController,
                private router: Router) {
    }

    get<T>(url: string) {
        return this.init().then(async () => {
            const loading = await this.loadingController.create({
                spinner: 'crescent',
                message: 'Please Wait'
            });

            await loading.present();
            return this.http.get<T>(environment.api_url + url, {headers: this.headers})
                .pipe(res => {
                        return res;
                    },
                    catchError((err, caught) => {
                        return this.handleError(err, caught);
                    }),
                    finalize(async () => {
                        await loading.dismiss();
                    }));
        });
    }

    post<T>(url: string, data: any) {
        return this.init().then(async () => {
            const loading = await this.loadingController.create({
                spinner: 'crescent',
                message: 'Please Wait'
            });

            await loading.present();
            return this.http.post<T>(environment.api_url + url, data, {headers: this.headers})
                .pipe(res => {
                        return res;
                    },
                    catchError((err, caught) => {
                        return this.handleError(err, caught);
                    }),
                    finalize(async () => {
                        await loading.dismiss();
                    }));
        });
    }

    async checkError(err) {
        // if (err.status === 401) { }
        // if (err.status === 500) { }
        await this.alertController.create({
            header: 'Error',
            message: 'Sorry, Something bad happend on our side.',
            buttons: ['Ok']
        }).present();
    }

    async init() {
        this.storage.get('token').then(token => {
            this.headers = new HttpHeaders().set('Authorization', 'Bearer ' + token);
        }).then(() => {
            const loading = await this.loadingController.create({
                spinner: 'crescent',
                message: 'Please Wait...'
            });

            await loading.present();
            // do some checking like version, connection, ...
            await loading.dismiss();
        });
    }
}

在我的组件中:

login(loginData: LoginModel) {
    return this.api.post('/auth/login', loginData)
        .then(data => {
            data.subscribe(res => {
                // json result of api call is avaiable here
            })
        });
}

推荐阅读