我的项目结构:
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";
}
待办事项-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);
}
}
待办事项-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
是list
和form
组件的父级
我启动应用程序,我在控制台中看到了:
但如果展开全部,我看到:
哪个结果是实际的,为什么在第二个视图中我看到1
和另一个2
。
答案 0 :(得分:2)
console.log' +'按钮只能显示对象的当前状态,而不能显示快照时的对象。
有关更深入的解释,请参阅console.log() async or sync?。
所以顺序:1,是对象的最终状态。
答案 1 :(得分:1)
永远不要在组件中使用提供程序(providers: [TodoService]
)
如
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']
})
export class AppComponent {
title:string = "Angular 2Do";
}
它在组件初始化时创建新实例,因此只将providers
放在模块中,即。 NgModule