Javascript 如何将angular app中的对象数组从一个组件传递到另一个组件
我正在开发angular应用程序。我想使用服务从一个组件到另一个组件创建一个对象数组。我正在使用以下链接 PassData.htmlJavascript 如何将angular app中的对象数组从一个组件传递到另一个组件,javascript,angular,typescript,Javascript,Angular,Typescript,我正在开发angular应用程序。我想使用服务从一个组件到另一个组件创建一个对象数组。我正在使用以下链接 PassData.html <div> <button type="button" [routerLink]="['/receive-data']">Pass Data</button> </div> 接收数据.ts import .... @Component({ selector: 'app-
<div>
<button type="button" [routerLink]="['/receive-data']">Pass Data</button>
</div>
接收数据.ts
import ....
@Component({
selector: 'app-PassData',
templateUrl: './PassData.component.html',
styleUrls: ['./PassData.component.css'],
providers: [DataService]
})
constructor( private dataService: DataService) { }
export class PassData {
passObjects : any[] = [{'name': 'John', 'city': 'paris'},{'name': 'Bob', 'city': 'london'}, {'name': 'Grim', 'city': 'paris'}];
passDataToService() {
this.dataService.storePassedObject(this.passObjects);
}
}
@Component({
selector: 'app-ReceiveData',
templateUrl: './ReceiveData.component.html',
styleUrls: ['./ReceiveData.component.css'],
providers: [DataService]
})
export class ReceiveData implements OnInit {
let selectedProducts = this.DataService.retrievePassedObject();
console.log(JSON.stringify(selectedProducts)); // prints empty array
}
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
allPassedData: any[] = [];
constructor() {}
storePassedObject(passedData) {
this.allPassedData = passedData;
}
retrievePassedObject() {
return this.allPassedData;
}
}
这是角度服务
DataService.ts
import ....
@Component({
selector: 'app-PassData',
templateUrl: './PassData.component.html',
styleUrls: ['./PassData.component.css'],
providers: [DataService]
})
constructor( private dataService: DataService) { }
export class PassData {
passObjects : any[] = [{'name': 'John', 'city': 'paris'},{'name': 'Bob', 'city': 'london'}, {'name': 'Grim', 'city': 'paris'}];
passDataToService() {
this.dataService.storePassedObject(this.passObjects);
}
}
@Component({
selector: 'app-ReceiveData',
templateUrl: './ReceiveData.component.html',
styleUrls: ['./ReceiveData.component.css'],
providers: [DataService]
})
export class ReceiveData implements OnInit {
let selectedProducts = this.DataService.retrievePassedObject();
console.log(JSON.stringify(selectedProducts)); // prints empty array
}
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
allPassedData: any[] = [];
constructor() {}
storePassedObject(passedData) {
this.allPassedData = passedData;
}
retrievePassedObject() {
return this.allPassedData;
}
}
这里有两个组件,passedData和ReceiveData,以及一个连接它们的服务,以便可以通过它们传递数据。我的目标是在ReceiveData组件中传递数据并打印传递的数据。当我检索发现数据为空的数据时,我不确定如何构造angular service
我已在app.module.ts中注册
这是app.module.ts
import ...
@NgModule({
declarations: [
PassData,
ReceieveData
],
providers : [
DataService
]
})
导出类AppModule{}
我知道所有经过的数据:任何[]=[];当我尝试从receiveData访问对象时,正在将数据设为空,它被重新分配给[]。但是如何解决这个问题呢?使用行为主体
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataService {
private paramSource = new BehaviorSubject(null);
sharedParam = this.paramSource.asObservable();
constructor() { }
changeParam(param: any[]) {
this.paramSource.next(param)
}
}
导入到组件
constructor(private _dataService: DataService) { }
更改参数
this._dataService.changeParam("your parameter")
读取参数
this._dataService.sharedParam.subscribe(param=>console.log(param))
使用BehaviorSubject
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataService {
private paramSource = new BehaviorSubject(null);
sharedParam = this.paramSource.asObservable();
constructor() { }
changeParam(param: any[]) {
this.paramSource.next(param)
}
}
导入到组件
constructor(private _dataService: DataService) { }
更改参数
this._dataService.changeParam("your parameter")
读取参数
this._dataService.sharedParam.subscribe(param=>console.log(param))
使用服务中的主题和行为主题。就像下面的例子。因此,在这种情况下,两个组件都可以订阅服务对象并发送数据。所以只要一个改变了,另一个就会得到数据
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
allPassedData: BehaviourSubject<any> = new BehaviourSubject<any>([]);
constructor() {}
storePassedObject(passedData) {
this.allPassedData.next(passedData);
}
// here instead of retrieve like this you can directly subscribe the property in your components
retrievePassedObject() {
return this.allPassedData;
}
}
// Passed Component
import ....
@Component({
selector: 'app-PassData',
templateUrl: './PassData.component.html',
styleUrls: ['./PassData.component.css'],
providers: [DataService] // inject in module for singleton instance
})
export class PassData {
passObjects : any[] = [{'name': 'John', 'city': 'paris'},{'name': 'Bob',
'city': 'london'}, {'name': 'Grim', 'city': 'paris'}];
constructor(private dataService DataService){};
passDataToService() {
this.dataService. allPassedData.next(this.passObjects); // here you emit
the objects
}
}
// Recieved Component
@Component({
selector: 'app-ReceiveData',
templateUrl: './ReceiveData.component.html',
styleUrls: ['./ReceiveData.component.css'],
providers: [DataService] // instead of injecting service in component inject
in module for sigleton instance.
})
export class ReceiveData implements OnInit {
selectProducts: any;
constructor(private dataService DataService){};
ngOnInit(){
this.dataService.allPassedData.subscribe((allPassedData)=>{
this.selectProducts = allPassedData;
console.log(JSON.stringify(this.selectedProducts)); // print the data
})
}
import ...
@NgModule({
declarations: [
PassData,
ReceieveData
],
providers : [
DataService
]
})
从'@angular/core'导入{Injectable};
@可注射()
导出类数据服务{
allPassedData:Behavior Subject=新的Behavior Subject([]);
构造函数(){}
storePassedObject(passedData){
this.allPassedData.next(passedData);
}
//在这里,您可以直接订阅组件中的属性,而不是像这样进行检索
RetrievePasseObject(){
返回此.allPassedData;
}
}
//通过组件
进口。。。。
@组成部分({
选择器:'app PassData',
templateUrl:'./PassData.component.html',
样式URL:['./PassData.component.css'],
providers:[DataService]//为singleton实例注入模块
})
导出类PassData{
passObjects:any[]=[{'name':'John','city':'paris'},{'name':'Bob',
‘城市’:‘伦敦’,{‘名字’:‘冷酷’,‘城市’:‘巴黎’};
构造函数(私有数据服务数据服务){};
passDataToService(){
this.dataService.allPassedData.next(this.passObjects);//在这里发出
物体
}
}
//接收组件
@组成部分({
选择器:“应用程序接收数据”,
templateUrl:'./ReceiveData.component.html',
样式URL:['./ReceiveData.component.css'],
提供者:[DataService]//而不是在组件注入中注入服务
在sigleton实例的模块中。
})
导出类ReceiveData实现OnInit{
选择产品:任何;
构造函数(私有数据服务数据服务){};
恩戈尼尼特(){
this.dataService.allPassedData.subscribe((allPassedData)=>{
this.selectProducts=allPassedData;
console.log(JSON.stringify(this.selectedProducts));//打印数据
})
}
导入。。。
@NGD模块({
声明:[
PassData,
接收数据
],
供应商:[
数据服务
]
})
希望它能有所帮助。在服务中使用主题和行为主题。如下面的示例。因此,在这种情况下,两个组件都可以订阅服务对象并发出数据。因此,每当一个组件更改时,另一个组件将获得该数据
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
allPassedData: BehaviourSubject<any> = new BehaviourSubject<any>([]);
constructor() {}
storePassedObject(passedData) {
this.allPassedData.next(passedData);
}
// here instead of retrieve like this you can directly subscribe the property in your components
retrievePassedObject() {
return this.allPassedData;
}
}
// Passed Component
import ....
@Component({
selector: 'app-PassData',
templateUrl: './PassData.component.html',
styleUrls: ['./PassData.component.css'],
providers: [DataService] // inject in module for singleton instance
})
export class PassData {
passObjects : any[] = [{'name': 'John', 'city': 'paris'},{'name': 'Bob',
'city': 'london'}, {'name': 'Grim', 'city': 'paris'}];
constructor(private dataService DataService){};
passDataToService() {
this.dataService. allPassedData.next(this.passObjects); // here you emit
the objects
}
}
// Recieved Component
@Component({
selector: 'app-ReceiveData',
templateUrl: './ReceiveData.component.html',
styleUrls: ['./ReceiveData.component.css'],
providers: [DataService] // instead of injecting service in component inject
in module for sigleton instance.
})
export class ReceiveData implements OnInit {
selectProducts: any;
constructor(private dataService DataService){};
ngOnInit(){
this.dataService.allPassedData.subscribe((allPassedData)=>{
this.selectProducts = allPassedData;
console.log(JSON.stringify(this.selectedProducts)); // print the data
})
}
import ...
@NgModule({
declarations: [
PassData,
ReceieveData
],
providers : [
DataService
]
})
从'@angular/core'导入{Injectable};
@可注射()
导出类数据服务{
allPassedData:Behavior Subject=新的Behavior Subject([]);
构造函数(){}
storePassedObject(passedData){
this.allPassedData.next(passedData);
}
//在这里,您可以直接订阅组件中的属性,而不是像这样进行检索
RetrievePasseObject(){
返回此.allPassedData;
}
}
//通过组件
进口。。。。
@组成部分({
选择器:'app PassData',
templateUrl:'./PassData.component.html',
样式URL:['./PassData.component.css'],
providers:[DataService]//为singleton实例注入模块
})
导出类PassData{
passObjects:any[]=[{'name':'John','city':'paris'},{'name':'Bob',
‘城市’:‘伦敦’,{‘名字’:‘冷酷’,‘城市’:‘巴黎’};
构造函数(私有数据服务数据服务){};
passDataToService(){
this.dataService.allPassedData.next(this.passObjects);//在这里发出
物体
}
}
//接收组件
@组成部分({
选择器:“应用程序接收数据”,
templateUrl:'./ReceiveData.component.html',
样式URL:['./ReceiveData.component.css'],
提供者:[DataService]//而不是在组件注入中注入服务
在sigleton实例的模块中。
})
导出类ReceiveData实现OnInit{
选择产品:任何;
构造函数(私有数据服务数据服务){};
恩戈尼尼特(){
this.dataService.allPassedData.subscribe((allPassedData)=>{
this.selectProducts=allPassedData;
console.log(JSON.stringify(this.selectedProducts));//打印数据
})
}
导入。。。
@NGD模块({
声明:[
PassData,
接收数据
],
供应商:[
数据服务
]
})
希望能有所帮助。使用服务中的行为主题Hi Sunny Goel,我不熟悉angular,你能描述我如何做参考下面我的答案了解代码结构和解决问题。使用服务中的行为主题Hi Sunny Goel,我不熟悉angular,你能描述我如何做参考下面我的答案了解代码st吗重新构造和解决问题。