主题RXJS自动reflesh Angular不起作用

发布于 2025-02-05 07:41:58 字数 3409 浏览 2 评论 0原文

在Angular创建任务后,我正在尝试自动删除桌子。

包括GetTask方法和表格的我的家庭控制器:

Home-Component:

ngOnInit(): void {
    if(this.token){
      this.taskService.autoRefresh().subscribe(() => {
        this.getTasks();
      });
      this.getTasks();
    }
  }

  openModal() {
    this.dialog.open(CreateTaskComponent);
  }

  getTasks(): void {
    this.taskService.get(this.token).subscribe(
      (response) => {
        if (response) {
          this.tasks = response.tasks;
        }else{
          this.status = 'Aún no tienes creadas tareas';
        }
      },
      (error) => {
        console.log(error)
      }
    );
  }

Home-tivew:

<div *ngIf="tasks && tasks.length > 0">
    <div class="row">
        <div class="col-md-12">
            <table class="table mt-3">
                <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Nombre</th>
                        <th scope="col">Estado</th>
                        <th scope="col">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let t of tasks">
                        <th scope="row">{{t.id}}</th>
                        <td>{{t.name}}</td>
                        <td [ngSwitch]="t.done">
                            <span *ngSwitchCase="0">Pendiente</span>
                            <span *ngSwitchCase="1">Hecho</span>
                        </td>
                        <td [ngSwitch]="t.done">
                            <span *ngSwitchCase="0">Hecho Editar Borrar</span>
                            <span *ngSwitchCase="1">Borrar</span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

我的创建组件(包括模式)

  onSubmit(): void {
    const task: ITask = this.createTaskForm.value
    this.taskService.create(task, this.token).subscribe(
      (response) => {
        if (response) {
          this.status = `Tarea ${response.task.name} creada!`;
        } else{
          this.status = 'Error al crear la tarea!';
        }
      },
      (error) => {
        console.log(error)
      }
    );
  }

我的任务服务:

  private _subject = new Subject<void>();

  constructor(private _http: HttpClient) {}

  autoRefresh(){
    return this._subject;
  }
  
  create(task: ITask, token: string): Observable<any> {

    const headers = new HttpHeaders()
    .set(
      'Content-Type',
      'application/x-www-form-urlencoded'
    )
    .set('Authorization', token);

    const body = new URLSearchParams();
    body.set('name', task.name);


    const url = `${apiUrl}create`;

    return this._http.post(url, body.toString(), { headers: headers }).pipe(
      tap(() => {
        this._subject.next();
      })
    );
  }

  get(token: string | null): Observable<any> {
    const url = `${apiUrl}get-tasks/${token}`;

    return this._http.get(url);
  }

为什么它不起作用?它不会给我任何错误或任何错误,它只是忽略了该主题,就好像它不存在或未正确应用。我希望你能帮我。问候。

i am trying to auto-refresh my table after i create a Task on Angular.

My home controller who include getTask method and the table:

home-component:

ngOnInit(): void {
    if(this.token){
      this.taskService.autoRefresh().subscribe(() => {
        this.getTasks();
      });
      this.getTasks();
    }
  }

  openModal() {
    this.dialog.open(CreateTaskComponent);
  }

  getTasks(): void {
    this.taskService.get(this.token).subscribe(
      (response) => {
        if (response) {
          this.tasks = response.tasks;
        }else{
          this.status = 'Aún no tienes creadas tareas';
        }
      },
      (error) => {
        console.log(error)
      }
    );
  }

home-view:

<div *ngIf="tasks && tasks.length > 0">
    <div class="row">
        <div class="col-md-12">
            <table class="table mt-3">
                <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Nombre</th>
                        <th scope="col">Estado</th>
                        <th scope="col">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let t of tasks">
                        <th scope="row">{{t.id}}</th>
                        <td>{{t.name}}</td>
                        <td [ngSwitch]="t.done">
                            <span *ngSwitchCase="0">Pendiente</span>
                            <span *ngSwitchCase="1">Hecho</span>
                        </td>
                        <td [ngSwitch]="t.done">
                            <span *ngSwitchCase="0">Hecho Editar Borrar</span>
                            <span *ngSwitchCase="1">Borrar</span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

My create component (who include Modal)

  onSubmit(): void {
    const task: ITask = this.createTaskForm.value
    this.taskService.create(task, this.token).subscribe(
      (response) => {
        if (response) {
          this.status = `Tarea ${response.task.name} creada!`;
        } else{
          this.status = 'Error al crear la tarea!';
        }
      },
      (error) => {
        console.log(error)
      }
    );
  }

my task service:

  private _subject = new Subject<void>();

  constructor(private _http: HttpClient) {}

  autoRefresh(){
    return this._subject;
  }
  
  create(task: ITask, token: string): Observable<any> {

    const headers = new HttpHeaders()
    .set(
      'Content-Type',
      'application/x-www-form-urlencoded'
    )
    .set('Authorization', token);

    const body = new URLSearchParams();
    body.set('name', task.name);


    const url = `${apiUrl}create`;

    return this._http.post(url, body.toString(), { headers: headers }).pipe(
      tap(() => {
        this._subject.next();
      })
    );
  }

  get(token: string | null): Observable<any> {
    const url = `${apiUrl}get-tasks/${token}`;

    return this._http.get(url);
  }

Why isn't it working? It doesn't give me any error or anything, it just ignores the Subject as if it didn't exist or wasn't properly applied. I hope you can help me. Regards.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半枫 2025-02-12 07:41:58

方法AutoreFresh()应该看起来像:

autoRefresh() {
 this._subject.asObservable();
}

因为您想订阅该主题,必须将其作为可观察的返回。

希望它有帮助。

编辑:

尝试以下操作:

您的任务服务:

private _subject = new Subject<void>();

  constructor(private _http: HttpClient) {}

  autoRefresh(){
    return this._subject.asObservable();
  }

  // new method
  refreshTable() {
    this._subject.next();
  }
  
  create(task: ITask, token: string): Observable<any> {

    const headers = new HttpHeaders()
    .set(
      'Content-Type',
      'application/x-www-form-urlencoded'
    )
    .set('Authorization', token);

    const body = new URLSearchParams();
    body.set('name', task.name);


    const url = `${apiUrl}create`;

    return this._http.post(url, body.toString(), { headers: headers })
  }

  get(token: string | null): Observable<any> {
    const url = `${apiUrl}get-tasks/${token}`;

    return this._http.get(url);
  }


您的创建组件:

onSubmit(): void {
    const task: ITask = this.createTaskForm.value
    this.taskService.create(task, this.token).subscribe(
      (response) => {
        if (response) {
          this.status = `Tarea ${response.task.name} creada!`;
          
          // call the new method "refreshTable()"
          this.taskService.refreshTable();
        } else{
          this.status = 'Error al crear la tarea!';
        }
      },
      (error) => {
        console.log(error)
      }
    );
  }



Method autoRefresh() should look like:

autoRefresh() {
 this._subject.asObservable();
}

Because you want to subscribe to the subject therefor it has to be returned as observable.

Hope it helps.

EDIT:

Try something like this:

Your task service:

private _subject = new Subject<void>();

  constructor(private _http: HttpClient) {}

  autoRefresh(){
    return this._subject.asObservable();
  }

  // new method
  refreshTable() {
    this._subject.next();
  }
  
  create(task: ITask, token: string): Observable<any> {

    const headers = new HttpHeaders()
    .set(
      'Content-Type',
      'application/x-www-form-urlencoded'
    )
    .set('Authorization', token);

    const body = new URLSearchParams();
    body.set('name', task.name);


    const url = `${apiUrl}create`;

    return this._http.post(url, body.toString(), { headers: headers })
  }

  get(token: string | null): Observable<any> {
    const url = `${apiUrl}get-tasks/${token}`;

    return this._http.get(url);
  }


Your create component:

onSubmit(): void {
    const task: ITask = this.createTaskForm.value
    this.taskService.create(task, this.token).subscribe(
      (response) => {
        if (response) {
          this.status = `Tarea ${response.task.name} creada!`;
          
          // call the new method "refreshTable()"
          this.taskService.refreshTable();
        } else{
          this.status = 'Error al crear la tarea!';
        }
      },
      (error) => {
        console.log(error)
      }
    );
  }



~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文