如何通过Angular 6中的服务将对象发送到不相关的组件? [英] How can I send object to unrelated component through a service in Angular 6?

查看:58
本文介绍了如何通过Angular 6中的服务将对象发送到不相关的组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我是Angular的新手,我正在尝试使用服务将对象从component1发送到component2。当我将结果记录到component2的控制台中时,它没有提供该对象的更新值,这可能是因为该服务已在第二个组件中重新初始化。您可以在这个问题上帮忙吗?

So I'm new to Angular and I'm trying to send an object from component1 to component2 using a service. When I log the result to the console in component2, it doesn't give me the updated value of the object and it's probably because the service is reinitialized in the second component. Can you help on this issue?

这是我的代码

 @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;
  }
}

Component1

Component1

@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);
  }
}

Component2

Component2

@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);
  }
}


推荐答案

因为您使用的是

 providers:[CodeServiceService]

在两个组件中都有,因此它正在为两个组件创建新的服务实例。

in both components, so it's creating new instance of service for both components.

使用提供者: app.module.ts

@NgModule({
   // ..... imports
    providers:[CodeServiceService]
   //..
})

在Angular 6中:

您可以在 service.ts 中使用以下代码,而不是添加 app.module.ts

you can use below code in service.ts, rather than adding in app.module.ts

@Injectable({
  providedIn: 'root',
})

这篇关于如何通过Angular 6中的服务将对象发送到不相关的组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆