Hello so my problem is that I am trying to make a shared-service because I need an array in an other component. It seems like the "sender" class is working also as the service class itself. Just the "reciever" class isn't getting any data through the description. What do I need to change here to get it working?
Service:
import { Injectable } from "@angular/core";
import { Observable, Subject } from 'rxjs';
import { Note } from '../note/note-data';
@Injectable()
export class DataService {
exchangeData$: Observable<Note[]>
private dataSubject = new Subject<Note[]>()
constructor() {
this.exchangeData$ = this.dataSubject.asObservable()
}
exchangeData(data) {
console.log(data)
this.dataSubject.next(data)
}
}
Sender Class:
import { Component, OnInit } from '@angular/core';
import { NoteComponent } from 'src/app/note/note-component';
import { Note } from 'src/app/note/note-data';
import { Content } from '@angular/compiler/src/render3/r3_ast';
import { ContentSearcher } from './searcher/ContentSearcher';
import { DataService } from './ChangeDataService/DataService';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'noteApp';
public notes: Note[] = [
new Note("example title 1", "blablablalblalalblablabla", new Date(5000), new Date(5000)),
new Note("example title 2", "example description 2", new Date(5000), new Date(5000)),
new Note("example title 3", "example description 3 noch mehr blablalblalbla", new Date(5000), new Date(5000))
]
public constructor(private dataService:DataService) {
this.dataService.exchangeData(this.notes)
}
deleteNote(note: Note) {
var index = this.notes.indexOf(note, 0);
this.notes.splice(index, 1);
}
Reciever class:
import { Component, OnDestroy } from "@angular/core";
import { ContentSearcher } from './ContentSearcher';
import { Note } from '../note/note-data';
import { DataService } from '../ChangeDataService/DataService';
import { Subscription } from 'rxjs';
@Component({
selector: 'content-searcher',
templateUrl: './content.searcher.html',
styleUrls: ['./content.searcher.css']
})
export class ContentSearcherComponent implements OnDestroy {
public notes: Note[] = []
private subscription:Subscription
public constructor(private dataService: DataService) {
console.log("notes (constructor before init): "+this.notes)
this.subscription = this.dataService.exchangeData$.subscribe((data) => {
this.notes = data
console.log("notes in content.searcher (CONSTRUCTOR): "+this.notes)
})
console.log("subscription: "+this.subscription)
}
searcher: ContentSearcher = new ContentSearcher()
matchingNotes: Note[]
onKey(event) {
console.log("notes in content.searcher: "+this.notes)
const inputValue = event.target.value
if (this.notes != null) {
this.matchingNotes = this.searcher.searchContent(inputValue, this.notes)
}
}
getMatchingNotes(): Note[] {
return this.matchingNotes
}
ngOnDestroy() {
this.subscription.unsubscribe()
}
}