基于Clever的Angular 4与Express之间通信框架的搭建

说到要通信了,肯定是整个框架的通信要抽象出一个服务来,所以难点就很具体了,写一个大家都能用的服务。

1. 在服务模块submit.service.ts中:

    import {Injectable} from '@angular/core';
    import {Http, Response} from '@angular/http';
    import {Headers, RequestOptions} from '@angular/http';
    import {ElectronService} from './/electron.service'
    import { Settings } from '../Settings';
    import 'rxjs/add/operator/toPromise';

    @Injectable()
    export class SubmitService {
            constructor(private http: Http, public electronService: ElectronService) {
        }

        getSubmit(submitUrl: string): Promise {
            return this.http.get(Settings.baseURL  + submitUrl, {withCredentials: true})
            .toPromise()
            .then((res: Response) => {
                const body = JSON.stringify(res.json());
                if (res.json().msg === '404') {
                    this.electronService.syncSend('key', 'Need to update!');
                }
                return body || '';
            })
            .catch(this.handleError);
        }

        postSubmit(submitUrl: string, params: string): Promise {
            const options = new RequestOptions({withCredentials: true});
            return this.http.post(Settings.baseURL + submitUrl, params, options)
            .toPromise()
            .then((res: Response) => {
                const body = JSON.stringify(res.json());
                if (res.json().msg === '404') {
                    this.electronService.syncSend('key', 'Need to update!');
                }
                return body || '';
            })
            .catch(this.handleError);
        }

        private handleError(error: Response | any) {
            // In a real world app, we might use a remote logging infrastructure
            let errMsg: string;
            if (error instanceof Response) {
                const body = error.json() || '';
                const err = body.error || JSON.stringify(body);
                errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
            } else {
                errMsg = error.message ? error.message : error.toString();
            }
            console.error(errMsg);
            return Promise.reject(errMsg);
        }
    }

2. 在业务模块登录(login.component.ts)中,提交POST请求的方式

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { SubmitService } from '../providers/submit.service';

@Component({
    templateUrl: 'login.component.html'
})
export class LoginComponent {
    errorMessage: string;
    constructor(private router: Router,
                private submitService: SubmitService) { }

    loginAction (loginname: string, loginpass: string) {
        let respData = '';
        if (!loginname || !loginpass) {return; }
            const loginUrl = '/login/login';
            const params = {
            loginName: loginname,
            loginPass: loginpass
        };
        this.submitService.postSubmit(loginUrl, JSON.stringify(params))
        .then(
            responseData  => respData = responseData,
            error =>  this.errorMessage = error)
        .then(() => {
                const x = JSON.parse(respData);
                if (x === '1') {
                    this.router.navigate(['/plugins/datatable']); // 这里涉及页面跳转,跟ionic中的不同
                }else {
                    alert('登录失败!');
                }
            });
    }
}

3. 在业务模块获取表格数据(datatable.component.ts)中,提交GET请求的方式

import { Component, OnInit  } from '@angular/core';
import { SubmitService } from '../../providers/submit.service'

@Component({
    templateUrl: 'datatable.component.html'
})
export class DataTableComponent implements OnInit {
    public data;
    public filterQuery = '';
    errorMessage: string;
    constructor(private submitService: SubmitService) {}
    ngOnInit() { this.getDataTable(); } //实现初始化即执行的接口
    getDataTable() {
        let respData = '';
        const longinUrl = '/login/tabledata';
        this.submitService.getSubmit(longinUrl)
        .then(
            responseData => respData = responseData,
            error =>  this.errorMessage = error)
        .then(() => {
            this.data = JSON.parse(respData);
        });
    }
    public toInt(num: string) {
        return +num;
    }
    public sortByWordLength = (a: any) => {
        return a.name.length;
    }
}

4. 该注册服务注册服务,在app.module.ts中

@NgModule({
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        AppRoutingModule,
        HttpModule,
        BsDropdownModule.forRoot(),
        TabsModule.forRoot(),
        ChartsModule
    ],
    declarations: [
        AppComponent,
        FullLayoutComponent,
        SimpleLayoutComponent,
        NAV_DROPDOWN_DIRECTIVES,
        BreadcrumbsComponent,
        SIDEBAR_TOGGLE_DIRECTIVES,
        AsideToggleDirective
    ],
    providers: [{
        provide: LocationStrategy,
        useClass: HashLocationStrategy
    }, SubmitService, ElectronService],
    bootstrap: [ AppComponent ]
})
export class AppModule { }

5. html页面数据绑定




以上,大概就可以了。

你可能感兴趣的:(基于Clever的Angular 4与Express之间通信框架的搭建)