你知道为什么它控制台日志两次,当我添加一个项目?



这是一个使用angular和firebase构建的简单笔记应用程序。主要的组件添加项目和显示项目。在我的ngOnInit()钩子中,我在从服务中获取所有数据后将console.log(this.notepads)放在右边。问题是,当我添加一个项目时,它会记录两次,你可以在上传的截图中看到。

我认为每次我添加一个项目时,我的ngOnInit()被调用两次。你们怎么看?

import { Component, OnInit } from '@angular/core';
import { NotepadService } from 'src/app/services/notepad.service';
import { Notepad } from 'src/app/model/note';
@Component({
selector: 'app-add-note',
templateUrl: './add-note.component.html',
styleUrls: ['./add-note.component.css']
})
export class AddNoteComponent implements OnInit {
title:boolean=false;
noteTitle:string;
noteDescription:string;
constructor(private notepadService:NotepadService) { }
ngOnInit(): void {
}
onSubmit() {
if(!this.title || !this.noteTitle) {
alert('Task is empty')
} else {
let note:Notepad = {
title:this.noteTitle,
description:this.noteDescription
}
this.noteTitle = ''
this.noteDescription = ''
this.title = false
this.notepadService.addNote(note)
}
}
}
import { Component, OnInit} from '@angular/core';
import { NotepadService } from 'src/app/services/notepad.service';
import { Notepad } from 'src/app/model/note';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-notepad',
templateUrl: './notepad.component.html',
styleUrls: ['./notepad.component.css']
})
export class NotepadComponent implements OnInit {
notepads:Notepad[]=[];
modal:boolean=false;
selectedNote:Notepad= {
id:'',
title: '',
description: ''
};
constructor(private notepadService:NotepadService) { 
}

ngOnInit(): void {
this.notepadService.getNotepads().subscribe(notepad=> {
this.notepads=notepad
console.log(this.notepads)
})
}
onSelect(note:Notepad){
this.modal = !this.modal
this.selectedNote = note;
}
onSubmit(reg:NgForm) {
const note = reg.value;
note.id = this.selectedNote.id
this.notepadService.updateNote(note)
this.modal = false
}
removeNote() {
if(confirm('Are you sure?')) {
this.notepadService.deleteNote(this.selectedNote)
this.modal = false
}
this.modal = false
}
}

NotePadService可能是[observable]类型,这意味着当一个可观察对象的属性改变UI/(在这种情况下你的控制台日志)被自动更新。导致两个控制台日志。

// subscribe() is a method of the Observable type. This is a utility that asynchronously or synchronously streams data to a variety of components or services that have subscribed to the observable.
this.notepadService.getNotepads().subscribe(notepad=> {
this.notepads=notepad
console.log(this.notepads)
})

你已经在这里分配了可观察对象(看看构造函数):

private notepadService:NotepadService

当你最初加载页面调用notpadservice控制台日志发生。

然后当你添加一个note属性时,可观察对象的更新会导致另一个控制台日志。

回答您关于ngOnInit()是否被调用两次的问题。

没有,因为两个控制台日志是由于[observable]类型而发生的。