Angular RC6 - create an injection service with your own data

I have a data model (there must be one instance in the application)

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

I think the best approach would be to return it through an injection 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? C created just before ...

change

In this method, getComputer()I need to emulate the network delay - set the timeout to 2 seconds. I used to 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 as follows:

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

Now I want to translate it to use Observables, and then put it in the main module.

After Gunter Zochbauer's answer, I tried to follow

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

VSC let res ... [ts] Supplied parameters do not match any signature of call target. (alias) new BehaviorSubject<T>(_value: T): BehaviorSubject<T>. BehaviorSubject rxjs/rx.

Günter Zöchbauer

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

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

: let s = new BehaviorSubject<Computer>();. , Computer ( next()) ​​2 - ngInit.

+4
1
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);
}

private computer = new BehaviorSubject<Computer>();

computer$ = this.computer.asObservable();

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

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

Source: https://habr.com/ru/post/1653659/


All Articles