我是学习Angular 2类型脚本的初学者。我想将一个组件之间的数据传递给另一个组件?
Serives.ts
import {Component, Injectable} from '@angular/core';
// Name Service
export interface myData {
myDataname:any;
}
@Injectable()
export class GetService {
sharingData:any={myDataname:"My data string"};
saveData(str:any){
alert("Save Data");
// console.log('save data function called' + JSON.stringify(str));
this.sharingData.myDataname=str;
console.log(JSON.stringify(this.sharingData.myDataname));
}
getData():any{
console.log('get data function called');
console.log(JSON.stringify(this.sharingData.myDataname)+ "Get dats service s");
return this.sharingData.myDataname;
}
}
First Component.ts
import { GetService } from '../service/get-service';
@Component({
selector: 'firstcomponent,
templateUrl: 'firstcomponent.html',
providers:[GetService]
})
export class firstcomponentDetails {
firstname:string;
lastname:string;
constructor(public getservice: GetService ) {
this.getservice= getservice;
submitForm(value: any):void{
console.log(' Personal Details Form submited!');
console.log(value);
this.getservice.saveData(value);
}
}
}
Second Component.ts
import { GetService } from '../service/get-service';
@Component({
selector: 'secondpage',
templateUrl: 'secondpage.html',
providers: [GetService],
})
export class SecondPage {
getDatavaluesServices:any;
constructor( public getservice:GetService){
this.getservice = getservice;
this.getDatavaluesServices=getservice.getData();
console.log(this.getDatavaluesServices );
}
}
这是我的代码。我试过这个代码将数据第一个组件传递给第二个组件。我得到字符串值my data string
。如何获得第一个组件值?
答案 0 :(得分:1)
您可以创建一个服务并将其导入主模块并从那里导出,然后将其注入您想要使用它的组件。
import { StateService } from '../../../core/state.service';
constructor(
@Inject(StateService) private stateSrvc: StateService
) {}
您的服务将是这样的:
@Injectable()
export class StateService {
someStateValue: string;;
}
这样您就可以创建单例服务,这意味着整个应用程序中将有一个服务实例,因此您可以从另一个组件中检索从一个组件设置的任何值,从而允许您在两个组件之间来回传递数据组件没有依赖于通过URL和Router Params传递数据。
如何维护该服务中的状态存储取决于您,您可以简单地声明上述变量并直接获取和设置值:
stateSrvc.someStateValue = 1234
或
someLocalVariable = stateSrvc.someStateValue
或者您可以在服务中设置getVariable
和setVariable
功能以获得更多控制权。
您还可以使用Observables和Subjects或BehaviorSubjects来使用RxJS存储状态。
答案 1 :(得分:0)
您应该由父组件或模块提供服务,以确保组件之间只共享一个实例。在实例化组件时,对子组件providers:[GetService]
重新创建服务。因此,您将丢失其他组件设置的数据。
如果您遵循指南Parent and children communicate via a service,您可以看到子组件没有执行通信的共享服务的提供程序,但父mission-control
组件每个只提供一个实例像my-astronaut
这样的孩子。
在mission-control
模板中,my-astronaut
组件通过*ngFor
指令多次实例化。
如果还不够,您可以使用singleton pattern为服务创建自己的提供商。 (另请参阅this答案中的实现方式。)以这种方式使用提供程序,您可以为任何组件提供服务。