I have simple post request, that I use to create messages. The problem is that the function sendMessage() will work the same way forever, sending the same message into DB even after I change text. This continues until I destroy the table.
Will be grateful for any help, new into Ng.
What I have tried:
The way I thaught to solve the problem was to unsubscribe immediately after request, but it seems that I do it wrong, cause message even does not appear into Db.
Service
@Injectable({
providedIn: 'root',
})
export class MessageService {
private url = environment.apiUrl + '/message';
constructor(private http: HttpClient) {}
public create(request: CreateMessageRequest): Observable<void> {
return this.http.post<void>(this.url, request);
}
}
TS
public sendMessage(message: string){
let request: CreateMessageRequest = {
Message: message,
}
const req = this.messageService.create(request).subscribe();
}
HTML
<form>
<textarea #refVariable [value]="test" type="text" placeholder="Write message"></textarea>
<button class="buttonTwo" type="submit" (click)="sendMessage(refVariable.value)"></button>
</form>
Also tried:
export class DialogsComponent implements OnInit, OnDestroy {
constructor(private messageService: MessageService){}
private unsubscribe$ = new Subject<void>();
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
public sendMessage(message: string){
let request: CreateMessageRequest = {
Message: message,
}
this.messageService.create(request)
.pipe(takeUntil(this.unsubscribe$))
.subscribe();
}
}
And this one:
export class DialogsComponent implements OnInit, OnDestroy {
constructor(private messageService: MessageService){}
alive: boolean = true
ngOnDestroy(): void {
this.alive = false;
}
public sendMessage(message: string){
let request: CreateMessageRequest = {
Message: message,
}
this.alive = true;
this.messageService.create(request)
.pipe(takeWhile(() => this.alive))
.subscribe();
}
}