0

我正在尝试将来自组件的输入值保存到我的数据服务中,例如输入用户名和输入密码,单击它会从服务中进行后调用,但实际输入位于一个单独的组件中,其中数据服务已导入。

如何绑定输入中的数据,以将其添加到数据服务中的变量中?

更新:我设法在 DataService 和我的组件之间转换数据。下面是代码。

更新 v2:我现在收到一个新错误“预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 Content-Type。” 试图解决这个问题。

更新v3:我设法让一切正常,检查下面的答案!

数据服务:

import { HttpClient, HttpRequest } from '@angular/common/http';

import { Injectable } from '@angular/core';

@Injectable()
export class DataService {
    username:string = '';
    password:string = '';

    convioURL:string;
    loginMethod:string;

    constructor(private http: HttpClient) {}

    getData() {
        this.convioURL = 'https://testurl.com/';
        this.loginMethod = '?testMethod&user_name='+ this.username +'&password='+ this.password +'&response_format=json';
        const req = new HttpRequest('POST', this.convioURL + this.loginMethod, {
            reportProgress: true
        });

        return this.http.request(req);
    }
    usernameKey(value: string) {
        this.username + value;
    }
    passwordKey(value: string) {
        this.password + value;
    }
}

零件:

import { Component, OnInit } from '@angular/core';
import { HttpEvent, HttpEventType } from '@angular/common/http';
import { DataService } from '../data.service';
import * as $ from 'jquery';

@Component({
  selector: 'app-step-01',
  templateUrl: './step-01.component.html',
  styleUrls: ['./step-01.component.scss']
})
export class Step01Component implements OnInit {

    data: any;
    usernameInput: any;
    passwordInput: any;
    constructor(private dataService: DataService) {
    }

    ngOnInit() {
    }

    usernameKey(event: any) {
       this.dataService.username = event.target.value;
    }
    passwordKey(event: any) {
       this.dataService.password = event.target.value;
    }

    private getLoggedIn() {
        this.dataService.getData().subscribe((event: HttpEvent<any>) => {
            switch (event.type) {
                case HttpEventType.Sent:
                    console.log('Request sent!');
                break;
                case HttpEventType.ResponseHeader:
                    console.log('Response header received!');
                break;
                case HttpEventType.DownloadProgress:
                    const kbLoaded = Math.round(event.loaded / 1024);
                    console.log(`Download in progress! ${kbLoaded}Kb loaded`);
                break;
                case HttpEventType.Response:
                    console.log(' Done!', event.body);
                    this.data = event.body;
                    console.log(this.data);
          }
        });
    }

}

这是我的 jQuery 代码,它工作得非常好,但我试图远离在这个应用程序上使用 jQuery,我希望能够以 angular5/typescript 的方式编写它。希望这可以帮助大家理解我正在尝试做的事情。

$("#ssoForm").submit(function(e) {
            e.preventDefault();
            var username = $('#username').val();
            var password = $('#password').val();

            var apiURL = 'http://testurl.com/?';
            var loginMethod = 'testMethod&user_name='+ username +'&password='+ password +'&response_format=json';


            $.post(apiURL + loginMethod, 
                function(data) {
                    if (data) {
                        var json = $.parseJSON(data)
                        console.log(json);

                        var consID = json.loginResponse.cons_id;

                        var ssoUser = 'fakeusername';
                        var ssoPassword = 'fakepassword';

                        var ssoMethod = 'fakeSSOMethod&response_format=json&login_name='+ ssoUser +'&login_password='+ ssoPassword + '&cons_id='+ consID;

                        $.post(apiURL + ssoMethod, function(ssoData) {
                            var res = $.parseJSON(ssoData);
                            console.log(res);
                        });
                    } else {
                        console.log('No Data!');
                    }
            });
        });

组件模板:

<form id="ssoForm">
    <table>
        <tr>
            <td>User Name:</td>
            <td><input id="username" name=user_name type=text size=15 maxlength="100" #box (keyup)="usernameKey($event)"></td>
        </tr>
            <tr>
            <td>Password:</td>
            <td><input id="password" name=password type=password size=15 maxlength="100" #box2 (keyup)="passwordKey($event)"></td>
        </tr>
        <tr>
            <td>Remember Me:</td>
            <td><input name=remember_me type=checkbox></td>
        </tr>
    </table>
    <input (click)="getLoggedIn()" type="submit"/>
</form>
4

1 回答 1

1

我通过在数据服务中设置一个新函数来解决我的最新问题,然后在我正在使用的组件中调用该函数。

在 DataService 中添加了以下内容:

logMeIn() {
    this.convioURL = 'https://www.testurl.com/';
    this.loginMethod = '?testMethod&user_name='+ this.username +'&password='+ this.password +'&response_format=json';
    this.http.post(this.convioURL + this.loginMethod, null)
      .subscribe(res => {
            this.loginRes = res;
            console.log(this.loginRes);
        }, (err) => {
          console.log(err);
        }
      );
 }

然后在我的组件模板中单击时调用它。

希望这可以帮助其他人在我的情况下!

于 2017-12-05T19:39:18.290 回答