我是学习 Angular 2 类型脚本的初学者。我想将一个组件之间的数据传递到另一个组件?
Serves.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;
}
}
第一个组件.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);
}
}
}
第二个组件.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 );
}
}
这是我的代码。我尝试将此代码将数据第一个组件传递到第二个组件。我正在获取字符串值我的数据字符串
。如何获取第一个组件值?
最佳答案
您可以创建一个服务并将其导入到主模块中并从那里导出,然后将其注入(inject)到您想要使用它的组件中。
import { StateService } from '../../../core/state.service';
constructor(
@Inject(StateService) private stateSrvc: StateService
) {}
您的服务将是这样的:
@Injectable()
export class StateService {
someStateValue: string;;
}
通过这种方式,您将创建一个单例服务,这意味着整个应用程序中将有一个该服务的实例,因此您从一个组件设置的任何值都可以从另一个组件中检索,从而允许您在组件之间来回传递数据组件,而无需依赖通过 URL 和路由器参数传递数据。
如何维护该服务中的状态存储取决于您,您可以简单地声明上面的变量并直接获取和设置值:
stateSrvc.someStateValue = 1234
或
someLocalVariable = stateSrvc.someStateValue
或者您可以在服务中设置 getVariable
和 setVariable
函数以获得更多控制。
您还可以使用 Observables 和Subjects 或BehaviorSubjects 来使用 RxJS 来存储状态。
关于angular - 在 Angular 2 类型脚本中,无需导航或路由即可将数据从一个组件传递到另一个组件的可能性有哪些?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43172663/