从共享服务获取数据angular2

时间:2016-12-28 09:05:52

标签: angular

我想要实现的是:使用uploaderService从第一个组件上传图像。成功上传后,我的服务器正在发送一个密钥作为HTTP 我能够从第一个组件访问/打印的响应。成功上载后,第一个组件将重定向到第二个组件。现在, 我想访问/打印/使用第二个组件中服务的密钥值(第一个组件已经可访问的密钥)。

我尝试的是:使服务成为可注入的共享服务。因此,如果我导入服务并使用构造函数启动它,它应该具有相同的功能 第一个组件正在使用的服务实例。因此,我在第一个组件中获得成功回调的价值应该是我的第二个 组件不知何故。这是我的代码。

nb:我已经为ngModule提供了服务。我想它现在已经足够共享,并且可以从我的两个组件完全访问。我成功使用该服务并获取第一个组件中的密钥。但不知道如何在第二个组件中获得它。胖箭功能 我很困惑。我不能通过在组件中调用它来从服务中的函数A获取变量x的值,如:

  

someassignablevariable = this.service.x;

我的第一部分:

import {Component, Output} from '@angular/core';
import { Uploader } from '../services/uploader';
import { MyUploadItem } from '../services/my-upload-item';
import {Router} from "@angular/router";

@Component({
    template: `
//tempate codes
    `
})

export class FirstComponent {
    constructor(public uploaderService: Uploader, private _router: Router) { }

    public pushKey: String;

    submit() {
        let uploadFile = (<HTMLInputElement>window.document.getElementById('sampleFile')).files[0];


        let myUploadItem = new MyUploadItem(uploadFile);

        this.uploaderService.onSuccessUpload = (item, response, status, headers) => {
            // success callback
            this.pushKey = response.toString();
            console.log('Push Key:'+ response.toString())
            this._router.navigate(['second-component']);
        };
        this.uploaderService.onErrorUpload = (item, response, status, headers) => {
            // error callback

            console.log(response.toString());
        };
        this.uploaderService.onCompleteUpload = (item, response, status, headers) => {
            // complete callback, called regardless of success or failure
            console.log(response.toString());
        };
        this.uploaderService.onProgressUpload = (item, percentComplete) => {
            // progress callback
            console.log(percentComplete);
        };
        this.uploaderService.upload(myUploadItem);
    }
}

我的第二部分:

import {Component, OnInit} from '@angular/core';
import {Uploader} from "../services/uploader";

@Component({
    template: `
    ....
    <p>Push Key: {{pushKey}}</p>               
    ....
    `
})


export class SecondComponent{

    constructor(public uploaderService: Uploader) { }

    pushKey: String;

    ngOnInit(){this.getKey()}

        getKey() {

            this.uploaderService.onSuccessUpload = (item, response, status, headers) => {
                // success callback
                this.pushKey = response.toString();
                console.log('Push Key:' + this.pushKey);
            };
            return this.pushKey;
        }
}

我的服务:

import { Injectable }  from '@angular/core';
import { UploadItem }  from './upload-item';

@Injectable()
export class Uploader {
    onProgressUpload = (item: UploadItem, progress: number) => {};
    onCompleteUpload = (item: UploadItem, response: any, status: any, headers: any) => {};
    onSuccessUpload = (item: UploadItem, response: any, status: any, headers: any) => {};
    onErrorUpload = (item: UploadItem, response: any, status: any, headers: any) => {};
    onCancelUpload = (item: UploadItem, response: any, status: any, headers: any) => {};

    constructor() { }

    upload(item: UploadItem) {
        if(this.isHTML5()) {
            this.xhrTransport(item);
        } else {
            this.onErrorUpload(item, 'Unsupported browser.', null, null);
        }
    }

    private isHTML5(): boolean {
        return !!((<any>window).File && (<any>window).FormData);
    }

    private xhrTransport(item: UploadItem) {
        let xhr  = new (<any>window).XMLHttpRequest();
        let form = new (<any>window).FormData();

        this.forEach(item.formData, (key: string, value: any) => {
            form.append(key, value);
        });

        form.append(item.alias, item.file, item.file.name);


        xhr.upload.onprogress = (event: any) => {
            let progress = Math.round(event.lengthComputable ? event.loaded * 100 / event.total : 0);
            this.onProgressUpload(item, progress);
        };

        xhr.onload = () => {
            let headers = this.parseHeaders(xhr.getAllResponseHeaders());
            let response = this.parseResponse(headers['Content-Type'], xhr.response);
            if(this.isSuccessStatus(xhr.status)) {
                this.onSuccessUpload(item, response, xhr.status, headers);
            } else {
                this.onErrorUpload(item, response, xhr.status, headers);
            }
            this.onCompleteUpload(item, response, xhr.status, headers);
        };

        xhr.onerror = () => {
            let headers = this.parseHeaders(xhr.getAllResponseHeaders());
            let response = this.parseResponse(headers['Content-Type'], xhr.response);
            this.onErrorUpload(item, response, xhr.status, headers);
            this.onCompleteUpload(item, response, xhr.status, headers);
        };

        xhr.onabort = () => {
            let headers = this.parseHeaders(xhr.getAllResponseHeaders());
            let response = this.parseResponse(headers['Content-Type'], xhr.response);
            this.onCancelUpload(item, response, xhr.status, headers);
            this.onCompleteUpload(item, response, xhr.status, headers);
        };

        xhr.open(item.method, item.url, true);

        xhr.withCredentials = item.withCredentials;

        this.forEach(item.headers, (name: string, value: string) => {
            xhr.setRequestHeader(name, value);
        });

        xhr.send(form);
    }

    private isSuccessStatus(status: number) {
        return (status >= 200 && status < 300) || status === 304;
    }

    private forEach(obj: any, callback: any) {
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                callback(i, obj[i]);
            }
        }
    }

    private parseHeaders(headers: string) {
        let dict = {};
        let lines = headers.split('\n');
        for (let i = 0; i < lines.length; i++) {
            let entry = lines[i].split(': ');
            if(entry.length > 1) {
                dict[entry[0]] = entry[1];
            }
        }
        return dict;
    }

    private parseResponse(contentType: string, response: string) {
        let parsed = response;
        if(contentType && contentType.indexOf('application/json') === 0) {
            try {
                parsed = JSON.parse(response);
            } catch(e) {
            }
        }
        return parsed;
    }

}

1 个答案:

答案 0 :(得分:0)

如果您为两个组件,组件1和组件2提供更高级别的服务,那么您的服务将是一个单独的服务。然后您的组件2将在服务中看到组件1对它做了什么。

例如:

(1)在您的服务中声明属性keyForUpload

(2)让组件1类在成功上传图像后更新keyForUpload

this.uploaderService.keyForUpload=123;

(3)现在,您的组件2可以访问keyForUpload

keyForUpload = this.uploaderService.keyForUpload // the value will be 123

这是可能的,因为您的两个组件都有一个服务实例。