koral
koral

Reputation: 2945

Angular RC6 - create injectable service with own data

I have a data model (should be single instance in application)

export class Computer {
    model: string;
    serial: string;
    completed: boolean = false;
}

I think the best approach would be to return it through injectable service.

@Injectable()
export class DataService {

    getComputer(): Observable<Computer> {
        let c = new Computer();
        c.model = 'Quite Good Computer 455';
        c.serial = '344-344-455-555';
        c.ompleted = true;
        ...
    }
}

It should be located in CoreModule.

How to implement DataService.getComputer() to return Observable ? The c created just before ...

edit

In this getComputer() method I need to emulate network latency - set timeout for 2s. Previously I was using Promise and this function was:

getComputer(): Promise<Computer> {
    return new Promise<Computer>(resolve =>
        setTimeout(() => resolve(this.createComputer()), 2000) // 2 seconds
    );
}

private createComputer(): Computer {
    let c = new Computer();
    c.model = 'Quite Good Computer 455';
    c.serial = '344-344-455-555';
    c.ompleted = true;
    return c;
}

It was consumed like this:

ngOnInit() {
    this.dataService.getComputer().then(
        data => this.computer = data
    );
}

Now I want to translate it into using Observables and later put inot core module.

After Günter Zöchbauer answer I tried following

getComputer(): Observable<Computer> {
    let res = new BehaviorSubject<Computer>();
    return <Observable<Computer>>res.asObservable();
}

but VSC highlights line let res ... with error message [ts] Supplied parameters do not match any signature of call target. (alias) new BehaviorSubject<T>(_value: T): BehaviorSubject<T>. I imported BehaviorSubject from rxjs/rx.

edit

After another note from Günter Zöchbauer I changed the service class code

export class DataServiceMock {
    private computerObs: Observable<Computer>;
    constructor() {
        let s = new BehaviorSubject<Computer>();
        this.computerObs = s.asObservable(); 
    }  

    getComputer(): Observable<Computer> {
        return this.computerObs;
    }

Now the mentioned error is in here: let s = new BehaviorSubject<Computer>();. In this scenario I also don't know how to add Computer instance to stream (using next()) with 2 seconds delay - I'd put it in ngInit.

Upvotes: 4

Views: 194

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657128

getComputer(): Observable<Computer> {
    let c = new Computer();
    c.model = 'Quite Good Computer 455';
    c.serial = '344-344-455-555';
    c.ompleted = true;
    return Observable.of(c);
}

update

private computer = new BehaviorSubject<Computer>();

computer$ = this.computer.asObservable();

// called when computer changes
updateComputer(Computer c) {
  this.computer.next(c);
}

used by the caller

this.dataService.computer$.subscribe(...)

Upvotes: 2

Related Questions