如何将对象从服务传递到Angular8中的组件?
我有一个问题,我想将对象列表从服务传递到组件。响应未定义 这是数据服务。服务: 这是组件视图-item.component.ts的ts如何将对象从服务传递到Angular8中的组件?,angular,typescript,angular8,Angular,Typescript,Angular8,我有一个问题,我想将对象列表从服务传递到组件。响应未定义 这是数据服务。服务: 这是组件视图-item.component.ts的ts 从'@angular/core'导入{Component,OnInit}; 从“../service/data service.service”导入{DataService}; @组成部分({ 选择器:“应用程序待办事项”, templateUrl:'./view item.component.html', 样式URL:['./查看项.component.scs
从'@angular/core'导入{Component,OnInit};
从“../service/data service.service”导入{DataService};
@组成部分({
选择器:“应用程序待办事项”,
templateUrl:'./view item.component.html',
样式URL:['./查看项.component.scss'],
})
导出类ViewItemComponent实现OnInit{
待办事项:{};
构造函数(私有数据服务:数据服务){}
恩戈尼尼特(){
this.todos=this.dataService;
this.dataService.loadAll();
log(this.dataService.data);
}
}
现在我只需要对象的console.log
谢谢 代码中存在大量语法错误 1) 您没有为服务中的
数据分配任何内容
2) 键/属性应该用逗号分隔,而不是分号
这应该可以解决它
在您的data-service.service.ts上
@Injectable()
export class DataService {
public data = {
"first": [
{
list: 'first',
id: 1,
title: 'First list title item',
description: 'Example description for first list title item',
completed: false,
}
],
"second": [
{
list: 'second',
id: 2,
title: 'Second list title item',
description: 'Example description for second list title item',
completed: false,
}
],
"third": [
{
list: 'third',
id: 2,
title: 'Third list title item',
description: 'Example description for third list title item',
completed: false,
}
],
};
loadAll(){
return this.data;
}
}
在component.ts上,您应该将服务中的loadAll()
方法返回的值分配到组件中的变量或属性中
import { Component, OnInit } from '@angular/core';
import { DataService } from '../service/data-service.service';
@Component({
selector: 'app-todo-item',
templateUrl: './view-item.component.html',
styleUrls: ['./view-item.component.scss'],
})
export class ViewItemComponent implements OnInit {
todos;
constructor(private dataService: DataService) {}
ngOnInit() {
this.todos = this.dataService.loadAll();
console.log(this.todos);
}
}
我复制了一个演示
import { Component, OnInit } from '@angular/core';
import { DataService } from '../service/data-service.service';
@Component({
selector: 'app-todo-item',
templateUrl: './view-item.component.html',
styleUrls: ['./view-item.component.scss'],
})
export class ViewItemComponent implements OnInit {
todos;
constructor(private dataService: DataService) {}
ngOnInit() {
this.todos = this.dataService.loadAll();
console.log(this.todos);
}
}