2

Делаю сервис со своей логикой но возникают ошибки:

  1. в сервисе:

Type 'Subscription' is not assignable to type 'Observable'.
Property '_isScalar' is missing in type 'Subscription'.

  1. в компоненте:

Argument of type '(params: ParamMap) => Subscription' is not assignable to parameter of type '(value: ParamMap, index: number) => ObservableInput<{}>'. Type 'Subscription' is not assignable to type 'ObservableInput<{}>'. Type 'Subscription' is not assignable to type 'ArrayLike<{}>'. Property 'length' is missing in type 'Subscription'.

компонент:

import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { UserServise } from '../users.service';
import { Location } from '@angular/common';
import { users } from '../home/home.component';
import { IUser } from '../IUser';
import 'rxjs/add/operator/switchMap';
@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css']
})
export class DetailsComponent implements OnInit {
  @Input() user: IUser;
  constructor(
    private userServise: UserServise,
    private route: ActivatedRoute,
    private location: Location
  ) { }

  ngOnInit(): void {
    this.route.paramMap
      .switchMap((params: ParamMap) => this.userServise.getLink(+params.get('id'))
      .subscribe(user => this.user = user));
  }
  goBack(): void {
    this.location.back();
  }
}

сервис:

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
import { users } from './home/home.component';
import { IUser } from './IUser';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/switchMap'
@Injectable()
export class UserServise {

  constructor(private http: Http) { }

  public getUsers() {
    return this.http.get('https://jsonplaceholder.typicode.com/users')
      .map(response => response.json())
      .map(users => {
        return users.map(({ id, name, username, email, address, phone, website }) => {
          return { id, name, username, email, address, phone, website }
        });
      });
  }
  public getLinks(): Observable<IUser[]> {
    return Observable.of(users);
  }
  // public getLinksSlowly(): Observable<IUser[]> {
  //   return new Promise(resolve => {
  //     // Simulate server latency with 2 second delay
  //     setTimeout(() => resolve(this.getLinks()), 2000);
  //   });
  // }
  public getLink(id: number): Observable<IUser> {
    return this.getLinks()
      .subscribe(users => users.find(
        user => user.id === id,
      ));
  }
}

1
  • вместо subscribe попробуй map
    – Grundy
    6 ноя 2017 в 21:30

1 ответ 1

1

.subscribe возвращает Subscription, а не Observable

Если вы хотите использовать значения дальше, а не здесь и сейчас - используйте map

import 'rxjs/add/operator/map';

this.getLinks()
  .map(users => ...);  

Попробуйте также явно указать тип ответа сервиса для switchMap:

.switchMap((params: ParamMap): Observable<IUser> =>  
  this.userServise.getLink(+params.get('id'))
5
  • это решило вопрос с сервисом но в компоненте осталась ошибка
    – Анна
    6 ноя 2017 в 21:34
  • Ошибка, вероятно, изменилась?
    – vp_arth
    6 ноя 2017 в 21:36
  • нет в компоненте осталась та же ошибка
    – Анна
    6 ноя 2017 в 21:38
  • Argument of type '(pa rams: ParamMap) => Subscription' is not assignable to parameter of type '(value: ParamMap, index: number) => ObservableInput<{}>'. Type 'Subscription' is not assignable to type 'ObservableInput<{}>'. Type 'Subscription' is not assignable to type 'ArrayLike<{}>'. Property 'length' is missing in type 'Subscription'.
    – Анна
    6 ноя 2017 в 21:42
  • Здесь: .switchMap((params: ParamMap): Observable<IUser> => this.userServise.getLink(+params.get('id')) нужен еще один параметр? а то выдает ошибку ',' expected
    – Анна
    6 ноя 2017 в 21:56

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.