Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core';
- import { Subscription } from 'rxjs';
- import { WebsocketService } from './websocket.service';
- import { Accommodation } from './accommodation/accommodation';
- const WS_URL: string = 'wss://api.night2stay.com/api/v2/websocket';
- const AUTHENTICATION_KEY: string = '4bd97223-9ad0-4261-821d-3e9ffc356e32';
- const ACCOMMODATION_KEY: string = '2ee1edbf-d90f-4785-b9db-5b07ce70a928';
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css'],
- providers: [WebsocketService],
- encapsulation: ViewEncapsulation.None
- })
- export class AppComponent implements OnDestroy, OnInit {
- private wsSubscription: Subscription;
- private searchHash: string = null;
- private lastid: number = 0;
- isSearchLocked: boolean = false;
- accommodations: Accommodation[] = [];
- constructor(private wsService: WebsocketService) {
- }
- subscribe() {
- this.wsSubscription = this.wsService.createObservableSocket(WS_URL)
- .subscribe(
- data => {
- let dataObject = JSON.parse(data);
- let accommodation: Accommodation = null;
- // 3. Чтобы отличить на какой запрос пришёл ответ, надо сверять «key» отправленного запроса
- // и полученного ответа. Они должны совпадать.
- if (dataObject.key === AUTHENTICATION_KEY)
- {
- // 1. Поиск запускать, только при успешной авторизации. Т.е. когда придёт ответ со статусом 200(status=”200”).
- if (dataObject.status === 200){
- this.getAccommodations();
- } else {
- alert("Authentication failed");
- }
- }
- else if (dataObject.key === ACCOMMODATION_KEY && dataObject.status === 200)
- {
- // 2. Повторять поисковый запрос чаще чем раз в 2 секунды не нужно.
- setTimeout(() => { this.isSearchLocked = false; }, 2000);
- // 4. Если поле “hash” в ответе при поиске такой же, как был до этого, то перестраивать список отелей не нужно.
- if (this.searchHash === dataObject.data.hash)
- {
- return;
- }
- else
- {
- this.accommodations.length = 0;
- }
- this.searchHash = dataObject.data.hash;
- dataObject.data.search.forEach((item: { info: any; items: any; }) => {
- let info = item.info;
- let items = item.items;
- accommodation = new Accommodation({
- id : info.id,
- name : info.name,
- addr : info.addr,
- img : info.img,
- stars: info.cat ? null : info.cat + 3,
- currency: items[0][0].commerce.currency,
- originalPrice: items[0][0].commerce.payment,
- discount: items[0][0].commerce.discount,
- discountPrice: items[0][0].commerce.tpayment
- });
- console.log(accommodation);
- if (this.lastid > dataObject.data.found)
- this.lastid = dataObject.data.found;
- this.accommodations.push(accommodation);
- });
- }
- },
- err => {console.log( err);},
- () => {
- console.log('The observable stream is complete');
- this.isSearchLocked = false;
- }
- );
- }
- authenticate () {
- this.isSearchLocked = true;
- let authMessage = `
- {
- "action":"login",
- "data": {
- "key":"123123 ",
- "wlcompany": "CMPN00000053"
- },
- "key":"${AUTHENTICATION_KEY}",
- "type":"account"
- }`
- if(!this.wsService.ws || !this.wsService.sendMessage(authMessage))
- {
- this.resubscribe();
- }
- }
- getAccommodations() {
- this.isSearchLocked = true;
- let query = `
- {
- "action": "accommodation",
- "data": {
- "place": {"in": "CI266088ZZ"},
- "date": {"in": 1551042000000,"out": 1551301200000},
- "families": [{"adults": 2}],
- "lastid": "${this.lastid}",
- "num": 5
- },
- "key": "${ACCOMMODATION_KEY}",
- "type": "service"
- }`
- if(!this.wsService.ws || !this.wsService.sendMessage(query))
- {
- this.resubscribe()
- }
- }
- resubscribe() {
- if (this.wsSubscription)
- this.wsSubscription.unsubscribe();
- this.subscribe();
- this.wsService.ws.onopen = () => {
- this.authenticate();
- };
- }
- getPrev5() {
- this.lastid = (this.lastid < 5) ? 0 : (this.lastid - 5);
- this.getAccommodations();
- }
- getNext5() {
- if (this.accommodations.length == 0)
- this.lastid = 0;
- else
- this.lastid = this.lastid + 5;
- this.getAccommodations();
- }
- ngOnInit() {
- this.getNext5();
- }
- ngOnDestroy() {
- this.wsSubscription.unsubscribe();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement