Skip to content

Commit e337c5b

Browse files
geromegrignond3lm
authored andcommitted
refactor: use inject() (#126)
1 parent 4a54f37 commit e337c5b

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

content/architecture/put-business-logic-into-services.md

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,34 +7,43 @@ title: put business logic into services
77
With Angular we are creating applications using a layered architecture. Every layer in our application should have its own responsibility. This means we have decoupled layers and each with its own concern.
88
Business logic in our application does not belong in the component layer. The component layer is purely meant to be used for visualization, displaying user interface and handling user input. Therefore, business logic should be extracted into the service layer.
99

10-
# Solution
11-
12-
In the following example, we are using the `HttpClient` to fetch data from a backend. This should not be done from the component layer but instead we move the logic into a dedicated service.
10+
In the following example, we are using the `HttpClient` to fetch data from a backend. This should not be done from the component layer.
1311

1412
```ts
1513
@Component({
1614
...
1715
})
18-
export class SomeComponent implements OnInit {
19-
data$;
16+
export class PeopleComponent implements OnInit {
17+
#httpClient = inject(HttpClient);
18+
people$ = this.http.get('http://some-api.com/api/people');
19+
}
20+
```
21+
22+
# Solution
2023

21-
constructor(private http: HttpClient) {}
24+
Let's move the logic into a dedicated `PeopleService` service instead!
2225

23-
ngOnInit() {
24-
this.data$ = this.http.get('http://some-api.com/');
26+
```ts
27+
@Injectable({
28+
providedIn: 'root'
29+
})
30+
export class PeopleService {
31+
#http = inject(HttpClient);
32+
33+
getPeople(): Observable<People[]> {
34+
return this.http.get<People[]>('http://some-api.com/api/people');
2535
}
2636
}
2737
```
2838

29-
We can refactor this and move the logic into a `PeopleService`.
39+
Now we can inject the `PeopleService` into our component and use the `getPeople` method.
3040

3141
```ts
3242
@Component({
3343
...
3444
})
35-
export class SomeComponent {
36-
data$ = this.peopleService.getPeople();
37-
38-
constructor(private peopleService: PeopleService) {}
45+
export class PeopleComponent {
46+
#peopleService = inject(PeopleService);
47+
people$ = this.peopleService.getPeople();
3948
}
4049
```

0 commit comments

Comments
 (0)