0

I'm trying to create data service in Angular which will be universal to all CRUD HTTP requests. However, I want public functions to return typed Observable<T>. So I figured I'd pass a type into my service's constructor, store in in local variable and then each client object to instantiate this service class would supply 'type' it expects from service's return functions so that my post, put, patch, delete and get would return already typed Observable. Something like this:

    export class DataService {
constructor(private http: HttpClient, private dataType: Type )
}

getAll(): Observable<dataType[]> {
return http.get<dataType[]>(...);
}

post(dataIn: dataType): Observable<dataType> {
    return http.post<dataType>(...);
}
}

Can it be done?

1
  • 1
    You seem to be confusing types and values. Also the value is this.dataType, not just dataType. If you just want to support interfaces you could make DataService generic, if you want to return actual instances of classes you'll have to implement that yourself. Commented Dec 16, 2022 at 22:45

2 Answers 2

2

Can it be done?

Kind of. You can achieve the result that you want, but not through the method that you are describing.

So I figured I'd pass a type into my service's constructor, store in in local variable

Types cannot be stored as variables because TypeScript types do not exist at runtime.

each client object to instantiate this service class would supply 'type' it expects from service's return functions

What you can do is turn DataService into a generic class. That means that each instance of DataService will have a different type T for its data.

You supply the type by setting the generic when you call the constructor:

const userService = new DataService<User>(client);
const commentService = new DataService<Comment>(client);

That generic class would look like this:

export class DataService<T> {
    constructor(private http: HttpClient) {
    }

    getAll(): Observable<T[]> {
        return this.http.get<T[]>(...);
    }

    post(dataIn: T): Observable<T> {
        return this.http.post<T>(...);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

What you want is to have a generic type for your service class. TypeScript is compiled to JavaScript and will lose all the types in this process. The Following example shows how to use generic types for classes:

export class MyClassService<T = DefaultType> {

  constructor(private http: HttpClient) {}

  getSomeData(): Observable<T> {
    return this.http.get<T>(...)
  }
}

1 Comment

Note this would not instantiate any classes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.