gnoumph
gnoumph

Reputation: 21

Angular 8/Ionic 5: "values is null" on POST request

Since yesterday, I'm stuck with an issue and I don't find anything to help me T.T

I'm working on an Angular 8 with Ionic 5 app for Android. I just want to make a POST request to an API. Yep, that's all ^^

I have a register.page.html with a register form, then on submit it calls the submitForm() function in register.page.ts.
This function calls the registerUser() function in user.service.ts. This is where I make the POST request to my API.

But everything goes wrong, and all I got is an error values is null in my console. The request is never send, and when I console.log my variables, everything seems fine.

Here are the files.

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 {
}

I don't understand why it doesn't works... If you have any idea, I really appreciate your help!
Thanks!

Upvotes: 0

Views: 1438

Answers (1)

gnoumph
gnoumph

Reputation: 21

Finally got it!

In api.service.ts, one header was initialized with a null value like this:

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

I have to change it with an empty value:

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

Upvotes: 1

Related Questions