简体   繁体   中英

Typescript return type for Observables in getter and setter

I'm building an app using Angular 2 with Typescript. What return type my setter and getter should have?

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Events, SqlStorage, Storage } from 'ionic-angular';
import { Subject } from 'rxjs/Subject';


export interface User {
  name?: string,
  email?: string,
  gender?: string,
  picture?: Object
}

export interface DataStore {
  user: User
}

@Injectable()
export class UserService {
  
  private storage: Storage;
  private _user$: Subject<User>;
  private dataStore: DataStore;

  constructor(
    private http: Http
  ) {
    this.storage = new Storage(SqlStorage);
    this._user$ = new Subject();
    this.dataStore = { user: {} };
  }

  set user$(user: User) {
    this.storage.set('user', JSON.stringify(user));
    this.dataStore.user = user;
    this._user$.next(this.dataStore.user);
  }

  get user$() {
    const subject = this._user$;
    const source = subject.asObservable();
    return source;
  }

}

I have tried this:

set user$(user: User): void {}
get user$(): Observable<User> {}

But throw these errors:

Error TS2380: 'get' and 'set' accessor must have the same type. Error

TS1095: A 'set' accessor cannot have a return type annotation. Error

TS2380: 'get' and 'set' accessor must have the same type. Error

TS2322: Type 'User' is not assignable to type 'Observable'.

Error TS2322: Type 'User' is not assignable to type

'Observable'. Property '_isScalar' is missing in type 'User'.

I think you're almost there but I question using the setter, at least in the code you have provided. When you look at the code inside your setter you're actually not setting anything to _user$.

I think this is what is tripping you up, I don't think you should be using a setter here. Based on what the code is doing inside your setter, this should just be a public function. This is what I think it should look like

constructor(private http: Http) {
  this.storage = new Storage(SqlStorage);
  this._user$ = new Subject();
  this.dataStore = { user: {} };
}

setUser(user: User) {
  this.storage.set('user', JSON.stringify(user));
  this.dataStore.user = user;
  this._user$.next(this.dataStore.user);
}

get user$() {
  return this._user$.asObservable();
}

Then your component that is using the Service, would call UserService.setUser(userObj).

When you follow errors messages, you will have only two pairs of setter and getter:

get var(): User {}
set var(user: User) {}

And

get var(): Observable<User> {}
set var(user$: Observable<User>) {}

Actually that are the only allowed combinations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM