Перейти к основному содержимому

Angular — DI, RxJS и формы


Маршрут Angular

ШагСтатья
1Первая программа
2Обзор
3Вы здесь

Внедрение зависимостей (DI)

Сервис — класс с @Injectable(); Angular создаёт экземпляр и передаёт в конструктор:

@Injectable({ providedIn: 'root' })
export class NotesService {
constructor(private http: HttpClient) {}

list() {
return this.http.get<Note[]>('/api/notes');
}
}
@Component({ /* ... */ })
export class NotesComponent {
notes$ = this.notesService.list();

constructor(private notesService: NotesService) {}
}

providedIn: 'root' — один экземпляр на приложение.


HttpClient и RxJS

HTTP-методы возвращают Observable, не Promise:

this.http.get<Note[]>('http://127.0.0.1:3000/notes').subscribe({
next: (data) => (this.notes = data),
error: (err) => console.error(err),
});

В шаблоне с async pipe подписка закрывается автоматически:

<li *ngFor="let note of notes$ | async">{{ note.text }}</li>

Основы RxJS: map, filter, switchMap (отмена старого запроса при новом поиске).


Маршрутизация

export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'notes', component: NotesComponent },
{ path: '**', component: NotFoundComponent },
];
<a routerLink="/notes">Заметки</a>
<router-outlet />

Формы

ТипКогда
Template-drivenПростые формы, ngModel
ReactiveСложная валидация, FormBuilder

Reactive example:

form = this.fb.group({
text: ['', [Validators.required, Validators.maxLength(2000)]],
});
<form [formGroup]="form" (ngSubmit)="save()">
<input formControlName="text" />
</form>

Standalone-компоненты

Современный Angular без NgModule для каждой фичи:

@Component({
standalone: true,
imports: [CommonModule, RouterLink],
template: `...`,
})
export class NotesComponent {}

Практика — 292.md.


Связанные материалы