puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

Services in Angular #13

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

Why there is Service in Angular?

Components shouldn't fetch or save data directly and they certainly shouldn't knowingly present fake data. They should focus on presenting data and delegate data access to a service. 组件不应该直接获取或保存数据,它们不应该了解是否在展示假数据。 它们应该聚焦于展示数据,而把数据访问的职责委托给某个服务。

Services are a great way to share information among classes that don't know each other. 服务是在多个“互相不知道”的类之间共享信息的好办法。

Before Angular injects the service to the relative component, the service has to be available by registering a provider (with an injector @Injectable() ).

A provider is something that can create or deliver a service. it instantiates the Service class to provide the service.

By Default, the Angular Cli command ng generate service -> provides with the root injector for the service.

@Injectable({
  providedIn: 'root',
})

Inject the service in the component, by adding a service inside the constructor ,then the functions inside the component could use the methods of the Service. And componentService should be pulic when we need to use or bind it in the template.

constructor(public componentService: Service){
    getComponentMethod():void{this.method = this.Service.getServiceMethod();}
}

it could also be possible to be put inside the ngOnInit(), let Angular call ngOnInit at an appropriate time after constructing

Notice that this method is a synchronous signature, which implies that the Service can fetch data synchronously, while in the reality, it needs to fetch the data from remote server, therefore, it needs to be asunchronous, therefore here we need to use Observable, cause Angular will use HttpClient.get to fetch the data, and Http.Client.get( ) will return a Observable. (https://angular.cn/guide/http)

Therefore the codes inside Service could be import { Observable, of } from 'rxjs';

getServiceMethod(): Observable<T[]>{
    return of(ARRAYS); //assuming the getServiceMethod will fetch the data from ARRAYS of remote server.
}

Inside the component.

getComponentMethod():void {
    this.Service.getServiceMethod().subscribe(
    )
}