在 Angular 中使用来自后响应的响应数据

时间:2021-01-09 11:21:42

标签: javascript angular post observable response

我有一个登录组件,其中的提交处理程序方法调用服务、订阅可观察对象并返回响应。问题是除了控制台记录响应之外,我无法弄清楚如何做任何事情,当尝试对数据做任何有用的事情时,我无法访问它。除了控制台从帖子返回的数据之外,没有任何示例说明如何做任何事情。

我知道它是异步的,我只是 Angular 的新手,对实现不是很清楚

登录表单组件.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth/auth.service';

@Component({
    selector: 'login-form',
    templateUrl: './login-form.component.html',
    styleUrls: ['./login-form.component.css']
})
    
export class LoginForm implements OnInit {
    
    constructor(
        private auth: AuthService
    ) {
        
    }
    public userName: string;
    public password: string;
    public asyncMsg: any = false;
    public response: object;

    ngOnInit(): void {
    }

    displayErrorMsg() {
        if (this.asyncMsg) {
            return this.asyncMsg;
        }
    }

    public submitHandler() {
        this.auth.postLogin({ username: this.userName, password: this.password })
            .subscribe(res => {
                console.log('res', res)
                return res;
            })

        console.log('this.response',this.response)

    }
    
}

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import config from '../../config';
import { Observable } from 'rxjs';

@Injectable({
    providedIn: 'root'
})

export class AuthService {

    constructor(
        private http: HttpClient,
    ) { }

    postLogin( credentials: object ): Observable<any>{
        return this.http.post(
            `${config.BASE_URL}auth/login`,
            credentials,
            {
                headers: { 'Content-Type': 'application/json' },
                observe: 'response'
            }
        )
    }
    
}

简单地说,我只是想让我的组件访问响应信息。

0 个答案:

没有答案
相关问题