Home > OS >  Observable is not assignable to type interface problem in angular
Observable is not assignable to type interface problem in angular

Time:03-23

I have below interface and model. Now I would like to get an observable after calling API. The code is below:

export class RegistrationListResultModel extends TaskResultModel {
    Users!: UserRegisterModel[];
}

export class UserRegisterModel {
    Id?: number;
    FirstName?: string;
    LastName?: string;
    Email?: string;
    Mobile?: string;
    OrgId?: number;
    Username?: string;
    Password?: string;
    PhotoUrl?: string;
    IsActive?: boolean;
    TimeZoneId?:string;
}

interface SearchResultUserRegistrationInfo {
    userLists: UserRegisterModel[];
    total: number;
}

I have the below function which calls an API and returns result as observable.

private _search(): Observable<SearchResultUserRegistrationInfo> {
        return this.service.get<RegistrationListResultModel>(`${this.apiPATH}lists`).pipe(map(data => {
            const {
                sortColumn,
                sortDirection,
                pageSize,
                page,
                searchFirstName,
                searchLastName,
                searchEmail,
                searchMobile,
                searchUsername
            } = this._state;

            let allMemberLists: UserRegisterModel[] = [];

            if (data) {
                allMemberLists = data.Users;

                // 1. sort              
                let userLists = sort(allMemberLists, sortColumn, sortDirection);

                const total = userLists.length;

                // 3. paginate
                userLists = userLists.slice((page - 1) * pageSize, (page - 1) * pageSize   pageSize);

                return { userLists, total };
            }
            else {
                // In case data is null
                return null
            }
        }));
    }

But I am getting the below errors:

Type 'Observable<{ userLists: UserRegisterModel[]; total: number; } | null>' is not assignable to type 'Observable'. Type '{ userLists: UserRegisterModel[]; total: number; } | null' is not assignable to type 'SearchResultUserRegistrationInfo'. Type 'null' is not assignable to type 'SearchResultUserRegistrationInfo'.ts(2322)

Can anyone help me to solve the errors

CodePudding user response:

Just change the signature of the your _search method:

private _search(): Observable<SearchResultUserRegistrationInfo | null> { ... }
  • Related