Итак, я новичок в Angular и пытаюсь отправить объект из component1 в component2 с помощью службы.Когда я записываю результат в консоль в 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);
}
}