CRUD服务-创建

时间:2018-08-30 09:29:31

标签: angular rest spring-boot

我目前正在开发带有Spring Boot Backend的第一个Angular(第6版)JS应用程序。 我已经有了一个用户概述,详细信息和编辑页面。 我可以编辑现有用户条目,但不能保存新用户。

我有一个userService来管理与后端的所有交互:

const httpOptions = {
 headers: new HttpHeaders({'Content-Type': 'application/json'})
};

@Injectable({
  providedIn: 'root'
})

export class UserService {

private apiUrl = 'http://localhost:8080/users';

constructor(private http: HttpClient,
            private messageService: MessageService) {
}

getUsers(): Observable<User[]> {
  return this.http.get<User[]>(this.apiUrl)
    .pipe(
      tap(user => this.log('fetched users')),
      catchError(this.handleError('getUsers', []))
    );
}

getUser(id: number): Observable<User> {
  const url = `${this.apiUrl}/${id}`;
  return this.http.get<User>(url).pipe(
    tap(_ => this.log(`fetched user id=${id}`)),
    catchError(this.handleError<User>(`getUser id=${id}`))
  );
}


updateUser(user: User): Observable<any> {
  const url = `${this.apiUrl}/${user.id}`;
  return this.http.put(url, user, httpOptions).pipe(
    tap(_ => this.log(`updated user id=${user.id}`)),
    catchError(this.handleError<any>('updateUser'))
  );
}

deleteUser(user: User): Observable<any> {
  const url = `${this.apiUrl}/${user.id}`;
  return this.http.delete(url, httpOptions).pipe(
    tap(_ => this.log(`delete user id=${user.id}`)),
    catchError(this.handleError<any>('deleteUser'))
  );
}

saveUser(user: User): Observable<any> {
  const url = `${this.apiUrl}/create`;
  this.log("user create with " + user.username +" and "+user.email);
  return this.http.put(url, user, httpOptions).pipe(
    tap(_ => this.log(`save user`)),
    catchError(this.handleError<any>('updateUser'))
  );
}

/**
 * Handle Http operation that failed.
 * Let the app continue.
 * @param operation - name of the operation that failed
 * @param result - optional value to return as the observable result
 */
private handleError<T>(operation = 'operation', result?: T) {
  return (error: any): Observable<T> => {

    console.error(error); // log to console instead

    this.log(`${operation} failed: ${error.message}`);

    // Let the app keep running by returning an empty result.
    return of(result as T);
  };
}

/** Log a HeroService message with the MessageService */
private log(message: string) {
  this.messageService.add(`UserService: ${message}`);
}
}

如果单击“保存”,则会看到“用户使用foo和foo@baar.com创建”的日志输出,但看不到其他任何内容。 没有请求发送到后端,但是也没有错误消息发生。

致谢, 扬尼克

0 个答案:

没有答案