首页 > 解决方案 > Angular 似乎对回调没有反应

问题描述

我有一个带有愿望清单的小型网络应用程序。添加项目有效。但是,在调用删除操作时,Angular 似乎并没有等待响应(既没有调用成功,也没有调用失败回调)。相反,角度导航到应用程序的根目录。

我已经定义了以下角度服务:

import {Item} from '../shared/Item.model';
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable()
export class UserService {

 baseUrl: String = 'http://localhost:8080/';

 constructor(private httpClient: HttpClient) {
  }

addWishListItem(userId: string, itemToAdd: Item) {
   return this.httpClient.post(this.baseUrl + '/rest/person/private/' + userId + '/wishlist', itemToAdd);
  }

 removeWishListItem(userId: string, itemToRemove: Item) {
    return this.httpClient.delete(this.baseUrl + '/rest/person/private/' + userId + '/wishlist/' + itemToRemove.id);
  }
}

调用服务的组件如下:

import { Component, OnInit } from '@angular/core';
import {Item} from '../shared/Item.model';
import {UserService} from './user.service';
import {ActivatedRoute, Router} from '@angular/router';
import {User} from '../shared/User.model';

@Component({
  selector: 'app-wishlist',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css'],
  providers: [UserService]
})
export class UserComponent implements OnInit {

  user: User;

  constructor(private userService: UserService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.userService.getUser(this.route.snapshot.params['id'], false).subscribe(
      (user: User) => {
        this.user = user;
        if (this.user === undefined) {
          this.router.navigate(['notfound']);
      }
    }
   );
  }

  onItemAdded(itemData: Item) {
    this.userService.addWishListItem(this.user.privateId, itemData).subscribe(
      (user: User) => {
        this.user = user;
      }
    );
  }

  onItemRemoved(itemData: Item) {
    const oldId = this.user.privateId;
    this.userService.removeWishListItem(this.user.privateId, itemData).subscribe(
      (response) => {console.log('Hehe'); },
      (error) => {console.log('oops'); }
    );
  }
}

两个回调均未执行。在后端调用实际的删除操作(我可以在那里中断)。为了完成,这里是 Angular 组件调用的 (spring boot / kotlin) 服务:

@RestController
@RequestMapping("/rest/person")
class PersonEndpoint(

        private val personRepository: PersonRepository,
        private val personWithPrivateIdToFactory: PersonWithPrivateIdToFactory,
        private val wislistItemDomainFactory: WishListItemDomainFactory
) {


    /**
     * Adds a wishlistitem to a user if that user exists and returns the updated user.
     */
    @CrossOrigin(origins = ["http://localhost:4200"])
    @PostMapping("/private/{id}/wishlist")
    @Transactional
    fun addWishlistItem(@PathVariable("id") privateId: UUID,
                        @RequestBody item: WishlistItemTo): PersonWithPrivateIdTo {
        val person = personRepository.findByPrivateId(privateId);
        if (person != null) {
            person.addItem(wislistItemDomainFactory.toDomain(item))
            return personWithPrivateIdToFactory.toTo(personRepository.save(person))
        } else {
            throw NotFoundException("No such user found.");
        }
    }

    /**
     * Adds a wishlistitem to a user if that user exists and returns the updated user.
     */
    @CrossOrigin(origins = ["http://localhost:4200"])
    @DeleteMapping("/private/{id}/wishlist/{itemId}")
    @Transactional
    fun removeWishlistItem(@PathVariable("id") privateId: UUID,
                           @PathVariable("itemId") itemToRemove: Long) {
        val person = personRepository.findByPrivateId(privateId);
        if (person != null) {
            person.removeItemById(itemToRemove)
            personRepository.save(person)
        } else {
            throw NotFoundException("No such user found.");
        }
    }
}

添加效果很好:更新的用户被返回并显示在屏幕上。我最初希望删除以类似的方式工作(返回更新的用户),但我目前已经删除了它,因为我认为删除操作的主体可能被 Spring Boot 或 Angular 忽略了。但是,我需要对删除操作的完成做出反应以重新加载用户。

编辑:

由于请求了 html,因此这里是 usercomponent 的 html:

<div class="wishlisttitle">Wishlist of {{user?.name}}</div>

<app-wishlist-edit
  (itemAdded)="onItemAdded($event)"
  class="submargin"></app-wishlist-edit>

<div *ngIf="user !== undefined">

<div *ngIf="user.wishlist.items.length == 0 &&" class="topmargin">Empty. Please add elements.</div>

  <app-wishlist-item
    *ngFor="let item of user.wishlist.items"
    [wishListItem]="item"
    (itemRemoved)="onItemRemoved($event)"
  ></app-wishlist-item>

</div>

这是愿望清单项目组件的 html:

<div class="container">
  <div class="row">
    <div class="col-sm">
      <div class="card bg-light border-dark">
        <div class="card-body">
          <h5 class="card-title">{{item.name}}</h5>
          <p class="card-text"><a href="{{item.url}}">{{item.url}}</a></p>
          <a href="#" class="btn btn-danger" (click)="onRemoveClicked()">Remove Item</a>
        </div>
      </div>
    </div>
  </div>
</div>

对于编辑:

<div class="container">
  <div class="row">
    <div class="col-md-5">
      <label for="name"><i>Item (Short description)</i></label>
      <input [(ngModel)]="itemName" type="text" id="name" class="form-control">
    </div>
    <div class="col-md-5">
      <label for="url"><i>Link</i></label>
      <input [(ngModel)]="itemLink" type="number" class="form-control" id="url">
    </div>
    <div class="col-md-2 align-self-end">
      <button class="btn btn-success" (click)="onSubmit()">Add</button>
    </div>
  </div>
  </div>

编辑:

问题解决了:显然是触发了导航。更改此设置后,问题很快得到解决。

有什么建议么?非常感谢。

标签: angularspring-bootkotlin

解决方案


您的休息服务中的删除方法似乎没有返回响应。也许您可以添加return person成功删除。

您可能还想将您的 http 调用函数更改为类似的内容。

    removeWishListItem(userId: string, itemToRemove: Item) {
       return this.httpClient
          .delete(this.baseUrl + '/rest/person/private/' + userId + '/wishlist/' + itemToRemove.id)
          .map(response => response.json())
          .pipe(
             catchError(this.handleError)
          );

推荐阅读