Search code examples
javascriptangulardependency-injectioncomposition

angular 2 service injection issue


My project structure:

enter image description here

app.component.ts:

import { Component } from "@angular/core"
import { Todo } from './components/shared/todo.model'
import { todos } from "./components/shared/todo.data"
import {TodoService} from "./components/shared/todoService"
import {TodoService} from "./components/shared/todoService";

@Component({
    moduleId: module.id,
    selector: "app",
    templateUrl: "app.component.html",
    styleUrls: ['app.component.css'],
    providers: [TodoService]
})
export class AppComponent {
    title:string = "Angular 2Do";
}

todo-form.component.ts:

import {Component, Output, EventEmitter} from "@angular/core";
import {Todo} from "../shared/todo.model";
import {TodoService} from "../shared/todoService"

@Component({
    moduleId: module.id,
    selector: "todo-form",
    templateUrl: "todo-form.component.html",
    styleUrls: ["todo-form.component.css"],
})
export class TodoForm {
    ...
    constructor(private todoService:TodoService) {
        console.log(this.todoService);
        this.todoService.order = 2;
        console.log( this.todoService);
    }

}

todo-list.component.ts:

import {Component, Input, OnInit} from "@angular/core"

import { ITodo } from "../shared/todo.model"
import { TodoService } from "../shared/todoService"

@Component({
    moduleId: module.id,
    selector: "todo-list",
    templateUrl: "todo-list.component.html",
    styleUrls: ["todo-list.component.css"],
})
export class TodoListComponent implements OnInit {
    todos:ITodo[];

    ...

    constructor(private todoService:TodoService) {
        ...
        console.log(this.todoService);
        this.todoService.order=1;
        console.log(this.todoService);

    }
   ...

}

app is the parent of the list and form components

Whaen I start application I see in console:

enter image description here

but if expand all I see:

enter image description here

Which result actual and why in second view I see 1 and in another 2.


Solution

  • The console.log '+' button can only show you the current state of the object, not the object at the snapshot in time of when it was called.

    See console.log() async or sync? for a more in depth explanation.

    So order: 1, is the final state of the object.