Angular 2:Observable不从服务返回对象(嵌套)

时间:2016-11-10 07:07:28

标签: angular typescript nested observable angular2-services

我有一个返回用户对象的角度服务。用户对象具有自己的属性和一组墙。该服务将一个observable返回给调用组件。在服务中,我可以从http服务返回的json创建一个用户对象。但是,当我订阅我的组件中的服务时,返回的对象为null。我在这里做错了什么?

// user.ts

import { wall } from './wall';

export class user {
    Id: number;
    EntryType: number;
    UserType: number;
    SubscriptionType: number;
    IsCoach: boolean;
    Username: string;
    Email: string;
    Name: string;
    Password: string;
    Created: string;
    MemberWalls: wall[];
}
//wall.ts
export class wall {
    Title: string;
    ViewItem_Id: number;
}
//authentication.service.ts

authenticate(authRequest: login): Observable<user> {
        let url: string = this.apiUrl + AppSettings.LOGIN_SERVICE;
        let headers = new Headers({
            'Content-Type': AppSettings.CONTENT_TYPE_HEADER, //'; charset=utf-8',
            'client-secret': AppSettings.CLIENT_SECRET,
            'client-id': AppSettings.CLIENT_ID
        });

        let options = new RequestOptions({ headers: headers });

        return this._http.post(url, authRequest, options) // 
            .map(data => {
                this.authenticated(data);
            })
            .catch(this.handleError);

    }

    private authenticated(res: Response) {
        let body = res.json();
        if (body.StatusCode === 200) {
            localStorage.setItem('auth_token', res.headers.get("access-token"));
            let user1: user = body.Data;
            //The user object is fine here. 
            //That means that the json and the user class structure match perfectly
            console.log(user1);
            return body.Data || {};
        }
        else {
            return {};
        }
    }
//login.component.ts

login() {
        this.errorMessage = '';
        this.currentUser = null;

            this._authService.authenticate(this.loginModel)
                .subscribe(user1 => this.currentUser = user1,
                error => this.handleError( error));

  //The user1 returned by the service is always null.
    }

2 个答案:

答案 0 :(得分:4)

在映射发布请求的结果时,您缺少 return 语句。

在es6和ts中:

  • 使用括号定义箭头函数时,必须使用return语句。
  • 当没有括号定义箭头函数时,es6会自动生成一个return语句,返回箭头符号后面提供的表达式的值

例如:

let f = (data) => this.authenticated(data);;
// Or 
let f = (data) => { return this.authenticated(data); };

答案 1 :(得分:0)

接受Gunter的回答:

user1 => this.currentUser = user1是一个在数据到达时调用的函数。在您之前执行评论的地方的代码