Angular 2:如何显示控制台响应数据?

时间:2017-03-13 07:27:51

标签: angular typescript

我无法显示控制台响应数据。我不知道我的代码出错了。我提供了他们。 非常感谢你的帮助。

控制台响应

console response

  
    

account.service.ts

  
import { Injectable }    from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable }    from 'rxjs/Rx';
import { Account } from './account';
import { environment } from '../../../environments/environment';
import { UrlConstant } from '../../shared/constant/url-constant';

@Injectable()
export class AccountService {
 constructor(private http: Http) {
 }
 private headers = new Headers({ 'Content-Type': 'application/json' 
  });
 private authApiUri = environment['BP_AUTH_SERVER_URI'];
 listAccount(authToken: string): Observable<Account[]> {
   this.headers.set('Authorization', authToken);
   console.log(authToken, ')))))))))))))))))');
   returnthis.http.get(`${this.authApiUri}/${UrlConstant.ACCOUNT_LIST.replace('id' , '5682682637844480')}`, { headers: this.headers })
  .map(response => {
    console.log(response, 'LLLLLLLLLLLLLLL')
    let accounts: Account[] = [];
    response.json().accountList.forEach((accountResponse) => {
      let account = new Account(accountResponse.name , accountResponse.primaryEmailAddress, accountResponse.displayName);
      account.kazooAccountId = accountResponse.account_kazooAccountId;
      accounts.push(account);
    });
    return accounts;
  })
  .catch(this.handleError);
}
 private handleError(error: Response | any): Observable<any> {
   return Observable.throw(error.json());
 }
}
  
    

account.ts

  
export class Account {
name: string;
kazooAccountId: string;
primaryEmailAddress: string;
displayName: string;

  constructor(name: string, primaryEmailAddress: string, displayName: string) {
    this.name = name;
    this.primaryEmailAddress= primaryEmailAddress;
    this.displayName = displayName;
   }
  }
  
    

帐户routing.ts

  
import { Routes } from '@angular/router';
import { UrlConstant } from '../../shared/constant/url-constant';
import { AccountListingComponent } from './account-listing/account-listing.component';

export const accountRoutes : Routes = [
  {
    path : UrlConstant.ACCOUNT_LISTING,
    component : AccountListingComponent
  }
];

  export  const accountRoutingComponent = [ AccountListingComponent ];
  
    

帐户列表/帐户listing.html

  
<p>
  account-listing works!
</p>
<ul>
   <li *ngFor="let account of accounts">
     {{account.name}}
     {{account.kazooAccountId}}
     {{account.displayName}}
   </li>
</ul>
  
    

帐户列表/帐户listing.component.ts

  
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { CookieService } from 'angular2-cookie/services/cookies.service';

import { AppConstant } from '../../../shared/constant/app-constant';
import { Account } from '../account';
import { AccountService } from '../account.service';

@Component({
  selector: 'app-account-listing',
  templateUrl: './account-listing.component.html',
  styleUrls: ['./account-listing.component.css'],
  providers: [CookieService, AccountService]
})
export class AccountListingComponent implements OnInit {
  accounts: Account[];
  constructor(private accountService: AccountService, private router: Router, private cookieService: CookieService) {
 }

 ngOnInit() {
   this.listAccount();
 }

  listAccount() {
    const authToken: string = 
   this.cookieService.get(AppConstant.AUTH_TOKEN_COOKIE);
this.accountService.listAccount(authToken)
  .subscribe((accounts) => {
    console.log(accounts, 'KKKKKKKKKKKKKKKKKKKK')
    this.accounts = accounts;
  })
 }
}

3 个答案:

答案 0 :(得分:1)

不知道您的期望是什么,因为您可以看到回复与accounts不匹配。您的回答实际上与此相似:

{"id":"1","emailsFor":"emailsFor","name":"shree org one","offers":false}

其次,如果这与您的帐户匹配,则无需使用forEach迭代回复,您只需.map(res => res.json())

您的服务:

return this.http.get(...)
  .map(res => res.json())

在您的组件中,将该数据分配给变量,这里我只使用了data

data: Object = {};

this.accountService.listAccount(authToken)
  .subscribe(data => {
    this.data = data;
  });

然后您可以显示响应的内容,例如:

{{data?.id}} {{data?.emailsFor}} {{data?.name}}

这是如何显示来自您的回复的数据。您的问题表明您正在寻找与您的帐户相匹配的其他类型的回复。为此,您必须弄清楚如何获得您正在寻找的响应。

答案 1 :(得分:0)

class SomeClass:

    foo = 1

    def __init__(self, bar):
        self.bar = bar
        self.foo = 2

    @staticmethod
    def somemethod():
        # no access to self nor cls but can read foo via SomeClass.foo (1)
        foo = SomeClass.foo
        SomeClass.someclassmethod()
        ...

    @classmethod
    def someclassmethod(cls, ...):
        # access to cls, cls.foo (always 1), no access to bar
        foo = cls.foo
        ...

    def someinstancemethod(self, ...):
        # access to self, self.bar, self.foo (2 instead of 1 because of init)
        foo = self.foo
        bar = self.bar
        self.somemethod()
        self.someclassmethod()
        ...

答案 2 :(得分:0)

如果您的数据是XML格式,您可以尝试这种方式

 HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://www.yoururl.com");

        WebResponse response = myReq.GetResponse();

        Stream responseStream = response.GetResponseStream();

        XmlTextReader reader = new XmlTextReader(responseStream);

        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Text)
                Console.WriteLine("{0}", reader.Value.Trim());
        }

        Console.ReadLine();

或者您可以尝试这种方式:

 WebClient client = new WebClient();
        client.DownloadStringCompleted += (sender,args) => {
            if(!args.Cancelled && args.Error == null) {
                string result = args.Result; // do something fun...
            }
        };
        client.DownloadStringAsync(new Uri("http://foo.com/bar"));