Угловое наследование вводит разные экземпляры - PullRequest
0 голосов
/ 05 сентября 2018

У меня есть 2 компонента, которые одинаковы друг с другом. Единственным отличием являются их имена и некоторые заголовки HTML. Из-за этого я хочу использовать наследование.

Я создал абстрактный сервис:

export abstract class AbstractFilmListService {

  protected readonly API = WebUtils.RESOURCE_HOST_API + 'film/';


  constructor(protected client: HttpClient) {
  }

  deleteFilm(filmId: number) {
    return this.client.delete(this.API + filmId);
  }

  fetchFilms(): Observable<Film[]> {
    return this.client.get(this.API) as Observable<Film[]>;
  }
}

Подкласс 1:

@Injectable({
  providedIn: 'root'
})
export class FilmListService extends AbstractFilmListService {
  constructor(protected client: HttpClient) {
    super(client);
  }
}

Подкласс 2:

@Injectable({
  providedIn: 'root'
})
export class SeriesListService extends AbstractFilmListService{

  protected readonly API: string;

  constructor(client: HttpClient) {
    super(client);
    this.API = WebUtils.SERIES_API;
  }
}

Пока все в порядке. Но я хочу сделать то же самое с компонентами:

FilmListComponent:

@Component({
  selector: 'app-film-list',
  templateUrl: './film-list.component.html',
  styleUrls: ['./film-list.component.css']
})
export class FilmListComponent implements OnInit {

  constructor(protected client: HttpClient,
              protected router: Router,
              protected snackService: SnackService,
              protected filmListService: FilmListService // <- Problem is here !
              ) {
  }
//....

}

SeriesListComponent:

 @Component({
  selector: 'app-series-list',
  templateUrl: './series-list.component.html',
  styleUrls: ['./series-list.component.css']
})
export class SeriesListComponent extends FilmListComponent implements OnInit {

  constructor(protected client: HttpClient,
              protected router: Router,
              protected snackService: SnackService,
              protected filmListService: FilmListService // <- Problem is here!
  ) {
    super(client, router, snackService, filmListService);
  }

  ngOnInit() {
  }

}

Я хочу FilmListComponent объявить AbstractFilmListService вместо FilmListService, и когда он начинает внедрять службу, он должен внедрить FilmListService.

Точно так же SeriesListComponent должен объявить AbstractFilmListService вместо FilmListService, а когда он начинает вводить службу, он должен внедрить SeriesListService.

Я имею в виду нечто подобное:

export class FilmListComponent implements OnInit {

  constructor(
             // ...
              protected filmListService: AbstractFilmListService
              ) {
          this.filmListService = new FilmListService(); // Angular should do  something like this...
  }
//....

}

То же самое для SeriesListComponent:

export class SeriesListComponent implements OnInit {

  constructor(
             // ...
              protected filmListService: AbstractFilmListService
              ) {
          this.filmListService = new SeriesListService(); // Angular should do  something like this...
  }
//....

}

Я знаю, что Angular не создает новые сервисы для каждого компонента, он использует шаблон проектирования Singleton для внедрения зависимостей. Чтобы прояснить себя, я написал

"new SeriesListService(), new FilmListService()"

Как добавить разные экземпляры для разных компонентов, даже если их типы объявлены одинаковыми в constuructor?


Обновление

AppModule:

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HeaderComponent,
    HomeComponent,
    UserManagementComponent,
    ActorComponent,
    FilmComponent,
    SeriesComponent,
    ProductComponent,
    SafeUrlPipe,
    FilmListComponent,
    HeroComponent,
    CoverComponent,
    SeasonComponent,
    ChapterComponent,
    SeriesListComponent,
    ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    RoutingModule,
    TokenModule,
    MaterialModule,
    NgbTimepickerModule,
    HttpInterceptorModule
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {
}

1 Ответ

0 голосов
/ 05 сентября 2018

Если это не будет одно-сервисная служба, то, по моему мнению, не имеет смысла использовать providedIn.

Но чтобы ответить на ваш вопрос, если вы хотите использовать разные экземпляры этой услуги, вы должны предоставить услугу в аннотации @Component:

@Component({
  selector: 'app-series-list',
  templateUrl: './series-list.component.html',
  styleUrls: ['./series-list.component.css'],
  providers: [AbstractFilmListService] // <-- will create a new instance for this component
})
...