如果您仅在第二个模块中需要来自服务器的数据,则可以从任何需要它的组件调用该方法。否则,如果您需要这两个组件中的数据,则最好只向API发出一次请求以获取学生数据,没有理由获得相同的数据两次。所以,你可以再创建一个服务,以保持数据和组件之间的共享,例如,让我们创建data.service,并想象,这studentData
是一个简单的字符串:
/* imports */
@Injectable()
export class DataService {
public studentData: string;
public setStudentData(studentData: string): void {
this.studentData = studentData;
}
public getStudentData(): string {
return this.studentData;
}
}
在你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);
}
}
而且里面你Performance.Component.ts你可以从DataService
这样得到的数据:
/* imports */
/* @Component stuff */
export class PerformanceComponent {
constructor(
private _dataService: DataService
) {}
// get previously stored "response" from "data.service"
console.log(this._dataService.getStudentData());
}
如果学生分数从StudenService获得,请在Module2中注入这两个服务 – Eliseo