Angular似乎对回调没有反应

时间:2018-12-08 21:13:24

标签: angular spring-boot kotlin

我有一个带有愿望清单的小型Web应用程序。添加项目有效。但是,当调用删除操作时,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的要求,以下是用户组件的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>

编辑:

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

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

1 个答案:

答案 0 :(得分:0)

似乎您的rest服务中的delete方法没有返回响应。也许您可以在成功删除后添加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)
          );