shou2017.com
JP

Understanding the Angular Tutorial Step by Step ②

Fri Jul 3, 2020
Sat Aug 10, 2024

Adding a Service

Now, here’s something important: services.

The reason services are necessary is explained simply in the documentation:

You should not directly get or save data inside a component. Of course, you also shouldn’t intentionally pass fake data. Components should focus on presenting data, and delegate other processing to service classes.

Angular Dependency Injection

If you create a file with the ng generate service command, you’ll see that only the constructor is initialized, and there’s no ngOnInit, which is mainly for initialization in components.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class HeroService {

  constructor() { }

}

This is the basic form of a service. The rest of the explanation was easy to understand. To summarize with a diagram, it looks like this:

Understanding the Angular Tutorial Step by Step ②

I was able to understand navigation in the app without any particular issues. The only thing to note is Angular’s routing.

Well, as long as you know that Angular has this kind of routing, that’s enough for now.

constructor(
  private route: ActivatedRoute,
  private heroService: HeroService,
  private location: Location
) {}

Fetching Data from the Server

The key point here is definitely RxJS. By using RxJS, you can handle asynchronous processing intuitively. However, I feel that my understanding deepened even more after writing asynchronous processing in plain JS and then revisiting RxJS.

This concludes the Angular tutorial, but as with any learning, a solid foundation and continuous practice are essential.

See Also