📘
TypeScript with Angular: Services and Dependency Injection
Advanced
140 XP
55 min
Lesson Content
TypeScript with Angular
Angular is built with TypeScript and uses it extensively for dependency injection, decorators, and type safety.
Angular Component
@Component({
selector: 'app-user',
template: '{{ user.name }}'
})
export class UserComponent {
@Input() user!: User;
@Output() userChange = new EventEmitter();
constructor(private userService: UserService) {}
} Angular Service
@Injectable({
providedIn: 'root'
})
export class UserService {
private users: User[] = [];
getUsers(): Observable {
return of(this.users);
}
} Typed Forms
this.form = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]]
});Example Code
Understanding Angular TypeScript patterns
// Angular uses TypeScript extensively
// For practice, simulate Angular patterns
interface User {
id: number;
name: string;
email: string;
}
class UserService {
private users: User[] = [];
getUsers(): User[] {
return this.users;
}
addUser(user: User): void {
this.users.push(user);
}
}
const service = new UserService();
service.addUser({ id: 1, name: "John", email: "john@example.com" });
console.log(service.getUsers());Expected Output:
[ { id: 1, name: 'John', email: 'john@example.com' } ]Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code