所以我是 Angular 的新手,我正在尝试使用服务将对象从组件 1 发送到组件 2。当我将结果记录到 component2 中的控制台时,它没有给我对象的更新值,这可能是因为服务在第二个组件中重新初始化。你能帮忙解决这个问题吗?
这是我的代码
@Injectable({
providedIn: 'root'
})
export class CodeServiceService {
codeInfo:Code={
name:"",
text:"",
type:0
};
getCode(){
console.log(this.codeInfo);
return this.codeInfo;
}
setCode(result:Code){
this.codeInfo=result;
}
}
组件1
@Component({
selector: 'app-newscan',
templateUrl: './newscan.component.html',
styleUrls: ['./newscan.component.css'],
providers:[CodeServiceService]
})
export class NewscanComponent implements OnInit {
scannedCode:Code={
name:"name",
text:"text",
type:1
};
constructor(private service:CodeServiceService){}
saveInfo(){
this.service.setCode(this.scannedCode);
}
}
组件2
@Component({
selector: 'app-scan-list',
templateUrl: './scan-list.component.html',
styleUrls: ['./scan-list.component.css'],
providers:[CodeServiceService]
})
export class ScanListComponent implements OnInit {
newcode:Code={
name:"",
text:"",
type:0
};
constructor(private service:CodeServiceService){
}
ngOnInit(){
this.newcode=this.service.getCode();
console.log(this.newcode);
}
}