Home > Mobile >  Angular: xhrRequest do not send
Angular: xhrRequest do not send

Time:08-06

i got a service with a function for an http post request. For some reason the request is not sent. However, when I apply a subscription to the post, the request is executed.

In other services with identical structure have no problems to send a request in the same way without subscription.

What is the reason ?

export interface iChatbox {
  user: number;
  input: string;
}

@Injectable({
  providedIn: "root",
})
export class GlobalChatboxService {
  constructor(public http: HttpClient) {}

  pushMessage(data: iChatbox): Observable<iChatbox> {
    return this.http.post<iChatbox>(
      `${environment.apiEndpoint}/chatbox/message/send`,
      data
    );
  }
}

This one works:

  pushMessage(data: iChatbox): Subscription {
    return this.http
      .post<iChatbox>(`${environment.apiEndpoint}/chatbox/message/send`, data)
      .subscribe();
  }

This also works

  signin(user: UserAuthData): Observable<any> {
    return this.http.post<any>(`${environment.apiEndpoint}/login`, user);
  }

CodePudding user response:

Observables are lazy you need to manually subscribe to fire them. They will remain awake until you tell them to stop broadcasting values. Http verbs in Angular are powered by RxJS under the hood. That's why the return type is an observable. Subscribe either in service or in consumer components. That depends on your business need.

  • Related