Angular 8 / Ionic 5:POST请求中的“值为空”

问题描述 投票:0回答:1

从昨天开始,我遇到了问题,找不到任何可以帮助我的T.T

我正在使用适用于Android的Ionic 5应用程序开发Angular 8。我只想向API发出POST请求。是的,仅此而已^^

我有一个带有注册表的register.page.html,然后在提交时调用register.page.ts中的submitForm()函数。此函数在user.service.ts中调用registerUser()函数。这是我向我的API发出POST请求的地方。

但是一切都出错了,我得到的只是控制台中的错误values is null。该请求从不发送,当我console.log我的变量时,一切似乎都很好。

这里是文件。

register.page.html:

<ion-header>
    <ion-toolbar>
        <ion-buttons slot="start">
            <ion-back-button></ion-back-button>
        </ion-buttons>
        <ion-title>Créer un compte</ion-title>
    </ion-toolbar>
</ion-header>

<ion-content>
    <form (ngSubmit)="submitForm()">
        <ion-item lines="full">
            <ion-label position="floating">Nom d'utilisateur</ion-label>
            <ion-input [(ngModel)]="user.username" name="username" type="text" required></ion-input>
        </ion-item>

        <ion-item lines="full">
            <ion-label position="floating">Email</ion-label>
            <ion-input [(ngModel)]="user.email" name="email" type="email" required></ion-input>
        </ion-item>

        <ion-item lines="full">
            <ion-label position="floating">Mot de passe</ion-label>
            <ion-input [(ngModel)]="user.password" name="password" type="password" required></ion-input>
        </ion-item>

        <ion-row>
            <ion-col>
                <ion-button type="submit" color="danger" expand="block">Créer un compte</ion-button>
            </ion-col>
        </ion-row>
    </form>
</ion-content>

register.page.ts:

import {Component, OnInit} from '@angular/core';
import {UserService} from '../services/user.service';
import {User} from '../classes/user';

@Component({
    selector: 'app-register',
    templateUrl: './register.page.html',
    styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {

    user: User;

    constructor(
        private userService: UserService,
    ) {
        this.user = new User();
    }

    ngOnInit() {
    }

    submitForm(): void {
        this.userService.registerUser(this.user)
            .subscribe(res => {
                console.log(res);
            }, err => {
                console.error(err);
            });
    }

}

user.service.ts:

import {Injectable} from '@angular/core';
import {User} from '../classes/user';
import {ApiService} from './api.service';
import {HttpClient} from '@angular/common/http';
import {catchError, retry} from 'rxjs/operators';
import {Observable} from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class UserService {

    currentUser: User;

    constructor(
        private http: HttpClient,
        private apiService: ApiService
    ) {
    }

    registerUser(user: User): Observable<any> {
        return this.http
            .post<any>(this.apiService.apiUrl + '/users', user, this.apiService.httpOptions)
            .pipe(
                retry(3),
                catchError(this.apiService.handleError)
            );
    }
}

api.service.ts:

import {Injectable} from '@angular/core';
import {HttpHeaders} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';

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

    apiUrl = 'http://127.0.0.1:3000/api/v1';
    httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            Accept: 'application/json',
            Authorization: null,
        })
    };
    token = null;

    constructor() {
    }

    handleError(error): Observable<never> {
        let errorMessage = '';

        if (error.error instanceof ErrorEvent) {
            errorMessage = error.error.message;
        } else {
            errorMessage = 'Error code: ' + error.status + '\nMessage: ' + error.message;
        }

        return throwError(errorMessage);
    }
}

app.module.ts:

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {RouteReuseStrategy} from '@angular/router';

import {IonicModule, IonicRouteStrategy} from '@ionic/angular';
import {SplashScreen} from '@ionic-native/splash-screen/ngx';
import {StatusBar} from '@ionic-native/status-bar/ngx';

import {AppComponent} from './app.component';
import {AppRoutingModule} from './app-routing.module';

import {HttpClientModule} from '@angular/common/http';

@NgModule({
    declarations: [
        AppComponent,
    ],
    entryComponents: [],
    imports: [
        BrowserModule,
        IonicModule.forRoot(),
        AppRoutingModule,
        HttpClientModule,
    ],
    providers: [
        StatusBar,
        SplashScreen,
        {
            provide: RouteReuseStrategy,
            useClass: IonicRouteStrategy,
        },
    ],
    bootstrap: [
        AppComponent,
    ],
})
export class AppModule {
}

我不明白为什么它不起作用...如果您有任何想法,我非常感谢您的帮助!谢谢!

post angular8 angular-httpclient ionic5
1个回答
0
投票

终于知道了!

api.service.ts中,一个标头用这样的空值初始化:

httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'application/json',
        Accept: 'application/json',
        Authorization: null, // The bad guy.
    })
};

我必须将其更改为空值:

httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'application/json',
        Accept: 'application/json',
        Authorization: '', // The good guy.
    })
};
© www.soinside.com 2019 - 2024. All rights reserved.