在angular2服务中,当服务的原始属性的值更改时 - 相应的组件属性不会改变,就好像服务将用户定义的自定义类作为属性并且如果更改 - 组件反映了变化。 为什么,变更检测如何在这里工作? 在我的应用程序中 - 我有一个自定义对象(Book)数组的服务。当用户使用AddComponent将新对象添加到此数组时 - 即使没有将组件的属性重新分配给服务的属性,此添加也会反映在ViewComponent中,而当我使用基本类型进行服务时 - >更改不会反映在组件中。我需要知道变量检测在这两种情况下是如何工作的,为什么它会有所不同。 注意:我使用了routerreusestrategy,因此一次加载构造函数的路由组件不会重新加载其构造函数 - 能够验证一旦构造函数被调用 - 在路由回同一组件时不会再次调用它。 我的服务代码:
import { Injectable } from "@angular/core";
import { Book } from "../dto/book";
@Injectable()
export class BooksService{
private _books:Book[];
private addedNumber:Number;
getAddCount():Number{
return this.addedNumber;
}
constructor(){
this.addedNumber=0;
this._books=[];
let book=new Book(1,"akriti");
this._books.push(book);
}
addBook(book:Book){
let matchFound=false;
this._books.every(function(element){
if(element.id==book.id){
matchFound=true;
return false;
}
else
return true;
});
if(!matchFound){
this._books.push(book);
}
this.addedNumber=20;
console.log("number: "+this.addedNumber);
}
fetchBook():Book[]{
console.log("automatch");
return this._books;
}
}
我的组件代码显示书籍详细信息:
import { Component } from "@angular/core";
import { Book } from "../dto/book";
import { BooksService } from "../service/books.service";
@Component({
templateUrl:'./view.books.component.html'
})
export class ViewBooksComponent{
private bookss:any;
private book:any;
private count:Number;
constructor(private booksService:BooksService){
console.log("view books constructor");
this.bookss=this.booksService.fetchBook();
this.count=this.booksService.getAddCount();
}
}
组件的html代码:其中count不反映为20但Book []数组反映更改
View Books :
<div *ngFor="let boo of book">{{boo.id}}||{{boo.name}}</div>
Count is : {{count}}
将Book详细信息添加到服务的组件代码:在其addBook函数上单击,count显示为20.
import { Component } from "@angular/core";
import { BooksService } from "../service/books.service";
import { Book } from "../dto/book";
@Component({
templateUrl:'./add.books.component.html'
})
export class AddBooksComponent{
private books:Book[];
private id:number;
private name:string;
private count:Number;
constructor(private booksService:BooksService){
console.log("constructor addbook");
this.id=0;
this.name="";
this.books=this.booksService.fetchBook();
}
addBook(){
console.log("inside addbook function for ts");
let book=new Book(this.id,this.name);
this.booksService.addBook(book);
this.count=this.booksService.getAddCount();
}
}