javascript - 使用 api 显示列表的 Angular 8 问题

标签 javascript angular typescript

我在 Angular 8 中打印列表时遇到问题 这是我的代码 proposal-component.ts

import { Component, OnInit, Input } from "@angular/core";
import { ActivatedRoute, Params } from "@angular/router";
import { Proposal } from "./proposal";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs/Rx";
import { ProposalService } from "./proposal.service";

@Component({
  selector: "proposal-show",
  templateUrl: "proposal-show.component.html",
  styleUrls: ["proposal-show.component.css"],
  providers: [ProposalService]
})
export class ProposalShowComponent implements OnInit {
  constructor(
    private http: HttpClient,
    private route: ActivatedRoute,
    private proposalService: ProposalService
  ) {}
  @Input()
  proposal: Proposal;

  ngOnInit(): void {
    let proposalRequest = this.route.params.flatMap((params: Params) =>
      this.proposalService.getProposal(params["id"])
    );
    proposalRequest.subscribe(response => (this.proposal = response.json()));
  }
}

这是我的proposal.service.ts

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Proposal } from "./proposal";
import { Observable } from "rxjs/Rx";
import { throwError } from "rxjs";
import { map } from "rxjs/operators";
import { retry, catchError } from "rxjs/operators";

@Injectable()
export class ProposalService {
  private proposalsUrl = "http://localhost:3002/proposals";
  constructor(private http: HttpClient) {}
  getProposals(): Observable<Proposal[]> {
    return this.http.get<Proposal[]>(this.proposalsUrl).catch(this.handleError);
  }
  getProposal(id: number) {
    return this.http.get(this.proposalsUrl + "/" + id + ".json");
  }
  handleError(error) {
    let errorMessage = "";
    if (error.error instanceof ErrorEvent) {
      // client-side error
      errorMessage = `Error: ${error.error.message}`;
    } else {
      // server-side error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    console.error(errorMessage);
    return throwError(errorMessage);
  }
}

这是我的 app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { NgbModule } from "@ng-bootstrap/ng-bootstrap";
import { HttpClientModule } from "@angular/common/http";
import { AppComponent } from "./app.component";
import { HomepageComponent } from "./homepage/homepage.component";
import { AppRoutingModule } from "./app-routing.module";
import { DocumentsComponent } from "./documents/documents.component";
import { DocumentService } from "./documents/document.service";
import { ProposalComponent } from "./proposal/proposal.component";
import { ProposalNewComponent } from "./proposal/proposal-new.component";
import { ProposalShowComponent } from "./proposal/proposal-show.component";
import { ProposalService } from "./proposal/proposal.service";

import {
  NgbPaginationModule,
  NgbAlertModule
} from "@ng-bootstrap/ng-bootstrap";

@NgModule({
  declarations: [
    AppComponent,
    HomepageComponent,
    DocumentsComponent,
    ProposalComponent,
    ProposalNewComponent,
    ProposalShowComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    NgbModule,
    NgbPaginationModule,
    NgbAlertModule,
    HttpClientModule
  ],
  providers: [DocumentService, ProposalService],
  bootstrap: [AppComponent]
})
export class AppModule {}

这是我的展示页面

<div class="container">
  <div *ngIf="proposal" class="card proposal-card">
    <h1>{{ proposal.customer }}</h1>
    <div class="col-md-6">
      <div>
        <p>Hi {{ proposal.customer }},</p>

        <p>
          It was a pleasure getting to meet with you and review your project
          requirements, I believe it is a great fit for the types of
          applications that I build out. Please feel free to check out some of
          my past projects
          <a href="{{ proposal.portfolio_url }}">here</a>.
        </p>

        <p>
          To successfully build out the application I will be utilizing
          {{ proposal.tools }}, and a number of other tools to ensure that the
          project follows industry wide best practices.
        </p>

        <p>
          Ensuring that you are fully informed is one of my top priorities, so
          in addition to incorporating everything that we discussed, I will also
          be creating a project management dashboard and sending you a project
          update message daily so that you can have a transparent view of the
          development as it takes place.
        </p>

        <p>
          To accomplish the project and meet the requirements that we discussed,
          I am estimating that it will take
          {{ proposal.estimated_hours }} hours in development time to complete.
          The project should take {{ proposal.weeks_to_complete }} weeks to
          complete and with my hourly rate of {{ proposal.hourly_rate }}/hour,
          the estimated total will be
          {{
            proposal.hourly_rate * proposal.estimated_hours
              | currency: "USD":true:".0"
          }}.
        </p>

        <p>
          The next step from here is to set up a meeting to finalize the project
          and sign contracts.
        </p>

        <p>I am excited to working with you and build out this project.</p>
      </div>
    </div>
  </div>
</div>

我在控制台上有这个错误

core.js:6014 ERROR TypeError: response.json is not a function core.js:6014 ERROR TypeError: this.proposal is not a function at SafeSubscriber._next (proposal-show.component.ts:27) at SafeSubscriber.__tryOrUnsub (Subscriber.js:185) at SafeSubscriber.next (Subscriber.js:124) at Subscriber._next (Subscriber.js:72) at Subscriber.next (Subscriber.js:49) at MergeMapSubscriber.notifyNext (mergeMap.js:69) at InnerSubscriber._next (InnerSubscriber.js:11) at InnerSubscriber.next (Subscriber.js:49) at MapSubscriber._next (map.js:35) at MapSubscriber.next (Subscriber.js:49)

注意:API 工作正常,没有任何问题。 API 服务器在轨道上

最佳答案

core.js:6014 ERROR TypeError: response.json is not a function

您正在使用 HttpClient,因此无需对响应调用 json,因为它已被调用(由 Angular HttpClient)。尝试:

proposalRequest.subscribe(response => this.proposal = response);

关于javascript - 使用 api 显示列表的 Angular 8 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59173878/

相关文章:

javascript - 为什么 count++ 作为参数传递时不起作用

javascript - typescript 中基于两个值的数组迭代

typescript 声明 : Merge a class and an interface

javascript - OpenLayers getFeatures() 访问属性

angular - 从 Angular 2 中的历史记录中删除一个组件

javascript - 如何禁用youtube提供的右键单击选项

javascript - 如何将数据从 mongodb(使用 Mongoose 模块)传递到 Node js View (使用临时引擎 jade)?

javascript - javascript 中的 async/await 什么时候有用?

node.js - NodeJS 和 Angular 2

angular - 我如何专注于特定的垫子标签