user6408649
user6408649

Reputation: 1305

Can i send object in HttpParams?

I have interface where profileRoles field is an object

export interface IRegisterModel extends IModelWithToken {
    firstName: string;
    fatherName: string;
    lastName: string;
    email: string;
    dateBirth?: string;
    regionId: number;
    mobilePhone: string;
    profileRoles?: { isStudent: boolean };
}

I attempt send this to mvc controller. Below is an angular service method:

public register(registerModel: IRegisterModel): Observable<any> {
    const params = new HttpParams()
        .append("userName", registerModel.email)
        .append("firstName", registerModel.firstName)
        .append("fatherName", registerModel.fatherName)
        .append("lastName", registerModel.lastName)
        .append("email", registerModel.email)
        .append("mobilePhone", registerModel.mobilePhone)
        .append("registrationRegionId", registerModel.regionId.toString())
        .append("__RequestVerificationToken", registerModel.token);
        if (registerModel.dateBirth) {
            params.append("dateBirth", registerModel.dateBirth);
        }
        if (registerModel.profileRoles) {
            params.append("profileRoles.isStudent", registerModel.profileRoles.isStudent.toString());
        }
    return this.httpClient.post("/Account/Register", params);
}

registerModel.profileRoles.isStudent contains required value but is not append to params. I thing that profileRoles.isStudent is a wrong syntax. How can i fix it and append object to HttpParams?

Upvotes: 0

Views: 1492

Answers (2)

terahertz
terahertz

Reputation: 3491

According to HttpParams specifications, HttpParams is immutable.

This class is immutable - all mutation operations return a new instance.

https://angular.io/api/common/http/HttpParams

When you attempted to append new params, with

params.append("dateBirth", registerModel.dateBirth);

or

params.append("profileRoles.isStudent", registerModel.profileRoles.isStudent.toString());,

it didn't change your original params variable.

As mentioned in the first quote, all mutation operations return a new instance, hence, append() method returns a new HTTPParams object. Your code should work by simply reassigning it back to params object.

if (registerModel.dateBirth) {
    params = params.append("dateBirth", registerModel.dateBirth);
}
if (registerModel.profileRoles) {
    params = params.append("profileRoles.isStudent", registerModel.profileRoles.isStudent.toString());
}

Upvotes: 1

youssef elhayani
youssef elhayani

Reputation: 745

export interface IRegisterModel extends IModelWithToken {
firstName: string;
fatherName: string;
lastName: string;
email: string;
dateBirth?: string;
regionId: number;
mobilePhone: string;
profileRoles?: ISBolStud;}

export interface IsBolStud{ isStudent: boolean }

I think you should redifine your interface like this, I hope this will help you !

Upvotes: 0

Related Questions