Reputation: 61
I am using Angular 4.
I have two modules.
Module 1 is Student has a Service called StudentService which makes a web api call to get student score
Module 2 is Performance has a Service called PerformanceService and makes web api calls to get data related to performance
In Module 2, i need to use the student score (which we are already getting in module 1).
My question is, should i invoke StudentService in Student.Component.ts ? or Student.Service.ts ? What is the best practice of communication ?
Upvotes: 2
Views: 3950
Reputation: 60518
There is not really enough information to make an informed choice.
(All rhetorical questions meant for contemplation not needing you to answer them here.)
It would seem for encapsulation purposes that you would want your Performance service to return all of the data required for working with Performance data. So if that includes Student info then that service should consider providing both.
If the student info could be a "header", then maybe the student component should be reusable as a nested component on the Performance page. Then the Student info would be provided by the Student component nested within the Performance page.
Upvotes: 2
Reputation: 16384
If You need the data from server only in second module, You can invoke the method from any component, where You need it. Otherwise, if You need that data in both components, You better make a request to API only 1 time to get Student data, there is no reason to get the same data twice. So you can create another one service to keep data and share it between components, for example, let's create data.service and will imagine, that studentData
is a simple string:
/* imports */
@Injectable()
export class DataService {
public studentData: string;
public setStudentData(studentData: string): void {
this.studentData = studentData;
}
public getStudentData(): string {
return this.studentData;
}
}
In your Student.Component.ts:
/* imports */
/* @Component stuff */
export class StudentComponent {
constructor(
private _studentService: StudentService,
private _dataService: DataService
) {}
this._studentService.yourAPICallMethod()
.then(response => {
// store "response" to "data.service"
this._dataService.setStudentData(response);
}
}
And inside your Performance.Component.ts you can get data from DataService
like this:
/* imports */
/* @Component stuff */
export class PerformanceComponent {
constructor(
private _dataService: DataService
) {}
// get previously stored "response" from "data.service"
console.log(this._dataService.getStudentData());
}
Upvotes: 2