首页 > 解决方案 > 解析对象在打字稿中没有按预期工作

问题描述

下面的 line1 和 line 2 是否等于 line3?

let resultObject:UserProfileAPI  =JSON.parse(subscribed['additional-info']) as UserProfileAPI; //line 1
this.profile = new UserProfileAPI(new User(resultObject["external-profile"].firstname,resultObject["external-profile"].lastname,resultObject["external-profile"].email))//line2 
//this.profile = JSON.parse(subscribed['additional-info']) as UserProfileAPI; //uncommenting line3 doesn't work if swapped with line1 and line2. I suppose line 1 and line2 do the same thing together as line 3

我有这段代码。我无法理解为什么未注释的代码可以工作,但是将其与注释的代码交换则不起作用

profile:UserProfileAPI;
...
(result:Result)=> {
        console.log("In nav - result from user signin state ",result);
        let subscribed:UserSigninState = result.additionalInfo;
        console.log("new user signin state received:", subscribed);
        this.userLoggedIn = subscribed.isSignedIn;
        //success in login and got profile
        if(subscribed.isSignedIn ){
          if(subscribed['additional-info'] !== '') {
            let resultObject:UserProfileAPI  =JSON.parse(subscribed['additional-info']) as UserProfileAPI; //line 1 works
            this.profile = new UserProfileAPI(new User(resultObject["external-profile"].firstname,resultObject["external-profile"].lastname,resultObject["external-profile"].email))//line2 works
            //this.profile = JSON.parse(subscribed['additional-info']) as UserProfileAPI; //uncommenting line3 doesn't work if swapped with line1 and line2. I suppose line 1 and line2 do the same thing together as line 3
          }else{
            console.log('login successful but didn\'t get profile');
            this.profile = new UserProfileAPI(new User('unavailable','unavailable','unavailable'));
          }
        }
        //fail in login, additional-inifo should have reason
        if(!subscribed.isSignedIn ){
          if(subscribed['additional-info'] !== '') {
            this.navEvent.emit(new NavContext(subscribed['additional-info']));
          } else{
            console.log('login wasn\'t successful but didn\'t get the reason for error');
            this.navEvent.emit(new NavContext('login failed. Reason unknown'));
          }
        }
      }

我正在对上面的代码进行单元测试Jasmine。该规范测试成功登录后,服务器应发送客户端应存储的用户配置文件。

fit('should set user profile for successful signin attempt',()=>{
    let navComponent:NavComponentComponent = component;
    let userManagementService:MockUserManagementService = TestBed.get(UserManagementService);
    let user = new User('manu','chadha','test@test.com');//create a user
    let dummyUserProfile= new UserProfileAPI(user);//create a dummy profile using user
    console.log('dummy profile is ',dummyUserProfile);//prints 'dummy profile is ', UserProfileAPI{external-profile: User{firstname: 'manu', lastname: 'chadha', email: 'test@test.com', password: ''}} 
    console.log('dummy profile is JSON stringify',JSON.stringify(dummyUserProfile));//prints 'dummy profile is JSON stringify', '{"external-profile":{"firstname":"manu","lastname":"chadha","email":"test@test.com","password":""}}'
    let userSignInState = new UserSigninState(true,JSON.stringify(dummyUserProfile));//create part of response as string
    console.log('user signin state ',userSignInState);//prints 'user signin state ', UserSigninState{isSignedIn: true, additional-info: '{"external-profile":{"firstname":"manu","lastname":"chadha","email":"test@test.com","password":""}}'}
   let result:Result = new Result('success',userSignInState);
console.log('result is ',result);//prints 'result is ', Result{result: 'success', additionalInfo: UserSigninState{isSignedIn: true, additional-info: '{"external-profile":{"firstname":"manu","lastname":"chadha","email":"test@test.com","password":""}}'}}
userManagementService.signInStateSubject.next(result);//send response
    console.log('user profile is ',navComponent.profile);//prints user profile is ', Object{external-profile: Object{firstname: 'manu', lastname: 'chadha', email: 'test@test.com', password: ''}}
    expect(navComponent.profile).toBeTruthy();
    expect(navComponent.profile).toEqual(dummyUserProfile);
  });

如果我注释 line1 和 line2 并且仅使用 line3,则上述测试不适用于代码

if(subscribed['additional-info'] !== '') {
   //                let resultObject:UserProfileAPI  =JSON.parse(subscribed['additional-info']) as UserProfileAPI; //line1
      //              this.profile = new UserProfileAPI(new User(resultObject["external-profile"].firstname,resultObject["external-profile"].lastname,resultObject["external-profile"].email)) //line2
                    this.profile = JSON.parse(subscribed['additional-info']) as UserProfileAPI; //line3

对于上面,我得到错误Expected object to be a kind of UserProfileAPI, but was Object({ external-profile: Object({ firstname: 'manu', lastname: 'chadha', email: 'test@test.com', password: '' }) }).

标签: typescript

解决方案


推荐阅读