在Angular中,可以使用服务来保存对象。以下是一个保存对象的解决方法:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ObjectService {
private myObject: any;
constructor() { }
setObject(object: any) {
this.myObject = object;
}
getObject() {
return this.myObject;
}
}
setObject
方法保存对象。import { Component } from '@angular/core';
import { ObjectService } from './object.service';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
myObject: any;
constructor(private objectService: ObjectService) {}
saveObject() {
this.objectService.setObject(this.myObject);
}
}
getObject
方法获取保存的对象。import { Component } from '@angular/core';
import { ObjectService } from './object.service';
@Component({
selector: 'app-another-component',
templateUrl: './another-component.component.html',
styleUrls: ['./another-component.component.css']
})
export class AnotherComponent {
myObject: any;
constructor(private objectService: ObjectService) {}
getObject() {
this.myObject = this.objectService.getObject();
}
}
这样,你就可以在一个组件中保存对象,并在另一个组件中获取保存的对象了。