Kum*_*ain 0 angular2-services angular
目前我正在使用共享服务将数据从一个组件传递到其他组件我在第一个组件上设置值并尝试在另一端检索值,但我收到空数组这里是我的代码:
**Ist Compnent:**
@Component({
templateUrl: './landingPage.component.html',
styleUrls: ['./landingPage.component.css'],
providers: [LandingService],
})
export class LandingPageComponent {
constructor(private landingService:LandingService) {
}
@Input() Location:string;
@Input() Type:string;
search(){
//setting value in landing service
this.landingService.SearchData[0]=this.Location;
this.landingService.SearchData[1]=this.Type;
console.log(this.landingService.SearchData) ///this print the data succesfully but when try to access on
// 2nd compnent receive and empty arrat
}
Run Code Online (Sandbox Code Playgroud)
第二部分
@Component({
templateUrl: 'find.component.html',
styleUrls: ['find.component.css'],
providers: [find,LandingService]
})
export class IndexComponent implements OnInit {
searchData:Object=[];
constructor(private landingService: LandingService) {
}
ngOnInit() {
this.searchData=this.landingService.SearchData; .// getting data of my landing servie that i have set in first component
console.log(this.searchData);//getting empty array
}
Run Code Online (Sandbox Code Playgroud)
LandingService
import {Injectable} from "@angular/core";
@Injectable()
export class LandingService {
SearchData:any=[];
}
Run Code Online (Sandbox Code Playgroud)
另外,我使用getter和setter进行了检查,但仍面临同样的问题,任何人都可以建议我做错了,因为我正在设置数据和控制台打印出我希望在第二个组件上接收的正确数据,但以一个空数组结束
该问题与您在组件中使用"providers"选项有关.
简短版本:
从两个单独的组件装饰器中删除providers选项,然后将其添加到包含这些组件(或AppModule)的NgModule中.
更新你的NgModule:
@NgModule({
imports: ...
declarations: ....
providers: [LandingService], /// <- add this
})
export class ......
Run Code Online (Sandbox Code Playgroud)
更新您的组件:
@Component({
templateUrl: './landingPage.component.html',
styleUrls: ['./landingPage.component.css'],
///providers: [LandingService], // <-- remove this from BOTH components
})
Run Code Online (Sandbox Code Playgroud)
长版:
当您向组件的providers数组添加服务时,您基本上是对Angular说,我想为此组件(及其子组件)提供此服务的新实例.因此,在您的示例中,您基本上告诉Angular您需要两个不同类型的LandingService对象,每个对应一个组件.由于它们是两个不同的实例/对象,因此它们每个都有自己的数据.
查看依赖注入系统的Angular文档以了解更多信息
| 归档时间: |
|
| 查看次数: |
471 次 |
| 最近记录: |