【问题标题】:Angular2 Passing parameters to web service http GETAngular2将参数传递给Web服务http GET
【发布时间】:2016-09-25 06:45:08
【问题描述】:

我有一个 profileComponent,它正在对服务端点进行 GET 调用,如下所示,AparmentService 被注入 bootstarp,因此没有提供者

@Component({
    selector: 'profile',
    template: `<h1>Profile Page</h1>

 {{userEmail.email}}
 {{profileObject | json}}
 `,
    directives: [ROUTER_DIRECTIVES]    
})

export class ProfileComponent implements OnInit {
    userEmail = JSON.parse(localStorage.getItem('profile'));
    public profileObject: Object[];


    constructor(private apartmentService: ApartmentService) { 
        this.apartmentService = apartmentService;
    }

    ngOnInit(): any {
        console.log(this.userEmail.email);                <--This value displays fine in the console 
        this.apartmentService.getProfile(this.userEmail.email).subscribe(res => this.profileObject = res);  <-- getting [] response for this 
        console.log(JSON.stringify(this.profileObject));   <-- undefined         
    }
}

服务看起来像这样

@Injectable()
export class ApartmentService {

    http: Http;
    constructor(http: Http) {
        this.http = http;
    }

    getProfile(userEmail :string){
       return this.http.get('/api/apartments/getprofile/:userEmail').map((res: Response) => res.json());
    } 
}

当我尝试使用参数直接在浏览器中点击端点时,我得到了响应。但不在 Angular 中。

有什么想法吗?

【问题讨论】:

    标签: node.js rest http angular


    【解决方案1】:

    http.get() 是异步的

    ngOnInit(): any {
        console.log(this.userEmail.email);                <--This value displays fine in the console 
        this.apartmentService.getProfile(this.userEmail.email).subscribe(res => this.profileObject = res);  <-- getting [] response for this 
        // at this position the call to the server hasn't been made yet.
        console.log(JSON.stringify(this.profileObject));   <-- undefined         
    }
    

    当来自服务器的响应到达时res =&gt; this.profileObject = res 被执行。 console.log() 在对服务器的调用甚至初始化之前进行

    改为使用

    ngOnInit(): any {
        console.log(this.userEmail.email);                <--This value displays fine in the console 
        this.apartmentService.getProfile(this.userEmail.email)
        .subscribe(res => {
          this.profileObject = res; 
          console.log(JSON.stringify(this.profileObject));
        });
    }
    

    我认为 URL 中的 :userEmail 没有达到您的预期。试试吧:

    getProfile(userEmail :string){
       return this.http.get(`/api/apartments/getprofile/${userEmail}`).map((res: Response) => res.json());
    } 
    

    【讨论】:

    • 只是添加那些花括号?我试过了,没有变化。
    • 抱歉,不知何故向上移动 console.log(...) 行丢失了。
    • 还是一样的行为。我认为我在传递参数时做错了什么。
    • 还是一样的行为。直接访问端点,而不是通过角度。试图在模板 {{profileObject | 中显示响应json}}
    • 我的错。我没有注意到您更改的 http get 中的反勾号。它正在处理您建议的更改。非常感谢。
    猜你喜欢
    • 2017-08-12
    • 2019-05-19
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    • 2015-08-10
    • 2018-12-06
    相关资源
    最近更新 更多