Is it possible to inject interface with angular2?

后端 未结 5 1532
不思量自难忘°
不思量自难忘° 2020-12-02 14:06

i wonder if there is a proper way to inject interfaces in Angular2? (cf. below)

I think this is related with the missing @Injectable() decorator on the interface, bu

5条回答
  •  日久生厌
    2020-12-02 14:50

    Alternate solution for angular 9

    @Injectable()
    export class TodoListPublicService implements TodoListService {
      getTodos(): Todo[] {
        const todos: Todo[] = [
          {
            title: 'get groceries',
            description: 'eggs, milk, etc.',
            done: false
          }
        ];
    
        return todos;
      }
    }
    

    create an abstract class

    export interface Todo {
      title: string;
      description: string;
      done: boolean;
    }
    
    @Injectable()
    export abstract class TodoListService {
      abstract getTodos(): Todo[];
    }
    

    Use in the component

    providers: [
        { provide: TodoListService, useClass: TodoListPublicService }
      ]
    export class TodoListComponent implements OnInit {
      todos: Todo[];
    
      constructor(private todoListService: TodoListService) { }
    
      ngOnInit() {
      }
    

提交回复
热议问题