【问题标题】:Facing problem in Subscribing Observable to component in Angular 8在 Angular 8 中订阅 Observable 组件时面临问题
【发布时间】:2020-01-26 11:21:13
【问题描述】:

我正在尝试通过 httpclient 获取数据,因为我使用了 Observable ,并尝试将该 Observable 订阅到组件 这样做我收到错误

this.res.job.map 不是函数 在 SignupComponent.jobTitle

SignupComponent.ts

    import { Component, OnInit } from '@angular/core';
    import { SignupService } from '../service/signup/signup.service';

    @Component({
      selector: 'app-signup',
      templateUrl: './signup.component.html',
      styleUrls: ['./signup.component.scss']
    })
    export class SignupComponent  {


     constructor(private fb: FormBuilder ,public res : SignupService ) { 
   this.jobtitle() }


    jobtitle(){
        this.res.jobTitle.map((res : Response) => res.json()).subscribe(result => {
          console.log(result);
        })
      }

    }

服务

     import { Injectable } from '@angular/core';
    import { observable, Observable } from 'rxjs';
    import { HttpClient } from '@angular/common/http';


    @Injectable({
      providedIn: 'root'
    })
    export class SignupService {

     constructor(public http: HttpClient) {}

  jobTitle() : Observable<any>{
     return this.http.get(this.jobTitle);
   }
    }

【问题讨论】:

标签: angular rxjs angular8 angular-httpclient angular-observable


【解决方案1】:

我们不需要使用 HttpClient 来映射它

另外你忘了在jobTitle() 函数中添加括号() 试试这样:

this.res.jobTitle().subscribe(result => {
  console.log(result);
})

【讨论】:

  • 我做了同样的事情,但我得到了错误 =>>>> 类型 '() => Observable' 上不存在属性 'subscribe'。
  • 修改了答案,是this.res.jobTitle()
【解决方案2】:

对于使用 RXJS 操作符(如 map、filter 等),您需要为每个操作符使用 pipe() 方法,并将您想要使用的所有操作符放入 pipe() 方法中。因此,操作符不是 RXJS 5.5 中引入的方法。

例如:

of(1,2,3).pipe(
  map(x => x + 1),
  filter(x => x > 2)
);

旧方式看起来像这样(现在它不起作用):

of(1,2,3).map(x => x + 1).filter(x => x > 2);

【讨论】:

    【解决方案3】:

    您好,错误试图告诉 oyu,res.jobTitle 不存在。 您正在使用它,就像您的服务 this.jobTitle 的一个字段一样,尽管没有。 因此undefined.map 不是一个函数。 除此之外,map() 只能在 pipe() 内部调用

    我也不确定你为什么使用 jobTitle 作为输入给你http.get()。 因为get() 想要一个 url 作为输入,其余的 oyur 代码就好像 jobTitle 应该是你的结果值一样。

    【讨论】:

      猜你喜欢
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 2018-03-10
      • 2020-06-19
      • 2017-10-18
      • 2017-11-30
      相关资源
      最近更新 更多