Как передать объект из сервиса компоненту в Angular8? - PullRequest
0 голосов
/ 25 октября 2019

У меня проблема, я хочу передать список объектов из службы компоненту. ответ не определен.

Это data-service.service :

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
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;
  }
}

Это ts компонента view-item.component.ts

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;
    this.dataService.loadAll();
    console.log(this.dataService.data);
  }
}

сейчас мне нужен только console.log объекта.

Спасибо!

1 Ответ

3 голосов
/ 25 октября 2019

В вашем коде есть куча синтаксических ошибок.

1) Вы не назначаете ничего для data в вашем сервисе.

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

Я воспроизвел демонстрацию поверх здесь .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...