【问题标题】:Unable to call api in angular无法以角度调用 api
【发布时间】:2019-01-31 22:43:02
【问题描述】:

我正在尝试使用 httpClinent 方法调用api,当我登录时,我得到的结果为 undefined

下面是services文件代码。

contact-service.services.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Customers } from 'src/app/mymodels/app.models';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class ContactServiceService {
 private baseUrl: string  = '............api URL..........';

 constructor(private http:HttpClient) { }

  getCustomers(){

   return this.http.get(this.baseUrl).subscribe(data => {});

  }

}

app.models.ts

 export interface Customers {
  id:                     string;
  firstName:              string;
  lastName:               string;
  fullName:               string;
}

组件代码

TS

 import { Component, OnInit } from '@angular/core';
 import {
   FormBuilder,
   FormControl,
   FormGroup,
  Validators,
   } from '@angular/forms';
import { map } from 'rxjs/operators';
import { Customers } from 'src/app/mymodels/app.models';
import { ContactServiceService } from 'src/app/Services/contact- 
    service.service';

 @Component({
  selector: 'app-get-contact',
  templateUrl: './get-contact.component.html',
  styleUrls: ['./get-contact.component.css']
 })

 export class GetContactComponent implements OnInit {
  public customers : Customers [];

  constructor(public customersService: ContactServiceService) { }

  ngOnInit() {
   this.customers = this.customersService.getCustomers();

    console.log(this.customers);  

   }

 }

HTML

<div *ngFor="let customer of customers">
  <p>{{customer.firstName}}</p>
</div>

【问题讨论】:

  • 在订阅中你没有返回任何东西

标签: angular angular6 angular-services


【解决方案1】:

你的服务代码就像,

getCustomers(){
   return this.http.get(this.baseUrl);
}

并在您的组件中调用 .subscribe,如下所示,

 ngOnInit() {
   this.customersService.getCustomers().subscribe((data)=> {
    this.customers = data;
    console.log(this.customers);  
});

【讨论】:

  • 收到此错误:错误在 src/app/get-contact/get-contact.component.ts(25,3): error TS1005: ',' 预期。
  • 缺少额外的 )。立即查看
猜你喜欢
  • 1970-01-01
  • 2021-04-29
  • 2021-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 2019-11-09
  • 1970-01-01
相关资源
最近更新 更多