@Sweg wrote:
The below code is used in an Ionic 5 / Angular tutorial to update a
Place
object. I am trying to apply this same code to my project where I update aConversation
object:Place Service:
private _places = new BehaviorSubject<Place[]>([ new Place( 'p1', 'Manhattan Mansion', 'In the heart of New York City.', 'https://lonelyplanetimages.imgix.net/mastheads/GettyImages-538096543_medium.jpg?sharp=10&vib=20&w=1200', 149.99, new Date('2019-01-01'), new Date('2019-12-31'), 'abc' ) ]); get places() { return this._places.asObservable(); } updatePlace(placeId: string, title: string, description: string) { return this.places.pipe( take(1), delay(1000), tap(places => { const updatedPlaceIndex = places.findIndex(pl => pl.id === placeId); const updatedPlaces = [...places]; const oldPlace = updatedPlaces[updatedPlaceIndex]; updatedPlaces[updatedPlaceIndex] = new Place( oldPlace.id, title, description, oldPlace.imageUrl, oldPlace.price, oldPlace.availableFrom, oldPlace.availableTo, oldPlace.userId ); this._places.next(updatedPlaces); }) ); }
And here is the
Place
model:export class Place { constructor( public id: string, public title: string, public description: string, public imageUrl: string, public price: number, public availableFrom: Date, public availableTo: Date, public userId: string ) {} }
As you can see, the above
updatePlace()
method can be subscribed to when called.I am trying to create an
addMessageToConversation()
method that can also be subscribed to, exactly like above.Here is my code so far:
Conversation Service:
private _conversations = new BehaviorSubject<Conversation[]>([ new Conversation( 'conversation1', 'user3', 'user1', [ new Message('message1', 'Test message', 'user3', new Date(2018, 0O5, 0O5, 17, 23, 42, 11)), new Message('message2', 'Another message', 'user1', new Date(2018, 0O6, 0O5, 17, 23, 42, 11)) ]) ]); get conversations() { return this._conversations.asObservable(); } addMessageToConversation(conversationId: string, message: string) { this._conversations.getValue().find(conversation => conversation.id === conversationId) .messages.push( new Message( Math.random().toString(), message, this.authService.userId, new Date(Date.now()) )); }
And here are the
Conversation
&Message
models:export class Conversation { constructor( public id: string, public userId: string, public mechanicId: string, public messages: Message[] ) { } } export class Message { constructor( public id: string, public text: string, public userId: string, public timestamp: Date ) { } }
The above code does update
conversations
, but I can’t subscribe to the method. Can someone please tell me what changes I need to make so that this is possible?If I
return
what is inaddMessageToConversation()
& try tosubscribe
to it, I get this error message:Property
subscribe
does not exist on type ‘number’
Posts: 1
Participants: 1