【问题标题】:Angular router - wrong url on redirection角度路由器 - 重定向时的错误网址
【发布时间】:2019-08-23 01:20:29
【问题描述】:

我对 Angular 路由有疑问。我正在尝试使用参数从一个页面重定向到另一个页面,结果我的浏览器尝试重定向到此链接: 'http://localhost:4200/resumes/%5Bobject%20Object%5D/edit' 而不是这个'http://localhost:4200/resumes/21/edit'。

app-routing.module.ts

{ path: 'resumes/:id/edit', component: EditResumeComponent } 

component.ts

import { Component, OnInit } from '@angular/core';
import { Resume } from 'src/app/models/Resume';
import { ResumeService } from 'src/app/services/resume.service';
import { Router } from '@angular/router';
import { UserService } from 'src/app/services/user.service';
import { AddUser } from 'src/app/models/AddUser';

@Component({
  selector: 'app-supply-contact-information',
  templateUrl: './supply-contact-information.component.html',
  styleUrls: ['./supply-contact-information.component.css']
})
export class SupplyContactInformationComponent implements OnInit {
  id: string;
  resume: Resume;

  constructor(
    private resumeService: ResumeService,
    private router: Router,
    private userService: UserService) { }

  ngOnInit() {
    this.resume = this.resumeService.getResume();
  }

  onSubmit() {
    this.resumeService.updateResume(this.resume);
    const addUserRequest = new AddUser(this.resume.firstName, this.resume.lastName, this.resume.email, this.resume.phone);

    this.userService.addUser(addUserRequest)
      .subscribe(value => this.id = value.toString(),
        () => {
          // TODO: On error should be implemented here!
        },
        () => {
          this.router.navigate([`/resumes/${this.id}/edit`]);
        });
  }
}

user.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { AddUser } from '../models/AddUser';
import { environment } from '../../environments/environment';
import { catchError, tap } from 'rxjs/operators';

const httpOptions = {
  headers: new HttpHeaders(
    {
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json'
    }),
};

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private apiUrl = environment.apiUrl;

  constructor(private http: HttpClient) { }

  addUser(addUserQuery: AddUser): Observable<number> {
    return this.http.post<number>(`${this.apiUrl}/user`, addUserQuery, httpOptions)
      .pipe(
        tap(() => this.log(`User with email: ${addUserQuery.email} created!`, false)),
        catchError(this.handleError<any>('addUser'))
      );
  }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(`${operation}: ${error}`);
      return of(result as T);
    };
  }

  // TODO: It should be implemented better later!
  private log(message: string, showNotification: boolean) {
    if (showNotification) {
      console.log(message);
    }
  }
}

我尝试像这样重定向,但得到相同的结果:

this.router.navigate(['resumes', id, 'edit']);

id 是一个普通的字符串属性,而不是一个对象。 AddUser 方法返回数字,所以我使用.toString() 方法将它变成一个字符串。

【问题讨论】:

  • 这表明 this.id 是一个对象。你能用局部变量吗:value.toString()
  • 这是正常的,字符串属性。
  • .subscribe(value =&gt; value here is an object..这就是value.toString()不提供id字符串的原因。
  • 也许您可以将其记录到控制台以确保它。
  • @tzm,明白了;这就是我的意思。现在您可以从值对象中获取 resumeId 并使用它。看看下面的答案

标签: angular routing angular7


【解决方案1】:

因为您的回复为:{"resumeId":31}

您应该使用 (resumeId from value 并将其用于导航):

this.userService.addUser(addUserRequest)
      .subscribe(value => this.id = value.resumeId.toString(),
        () => {
          // TODO: On error should be implemented here!
        },
        () => {
          this.router.navigate([`/resumes/${this.id}/edit`]);
        });

【讨论】:

  • 谢谢@nircraft ;-) 我已经在前端创建了带有 resumeId 属性的响应模型,并将服务方法返回值从数字更改为这个响应模型。比内部组件我只使用 'this.userService.addUser(addUserRequest).subscribe(addUserResponse => this.id = addUserResponse.resumeId)
猜你喜欢
  • 1970-01-01
  • 2019-03-30
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-17
相关资源
最近更新 更多